Is there a string remove method, that takes an index
Ali Çehreli
acehreli at yahoo.com
Tue Jan 29 19:27:15 PST 2013
On 01/29/2013 05:37 PM, Damian wrote:
> public string remove(string str, size_t start, size_t n) { }
>
> I need something like this, similar to .Net, does Phobos have this?
> I have looked at removechars in std.string and this is not suitable
for me.
> Do I need to roll my own?
Yes but it's extremely simple with a huge warning sign on it: :)
import std.stdio;
void main()
{
auto s = "neighbour";
s = s[0..7] ~ s[8..$];
assert(s == "neighbor");
}
The program is correct only if the string is a dchar string or it
contains ASCII characters only.
The correct apprach is to treat strings as what they are: dchar ranges.
Looks like removeAt() is pretty easy to implement when there is no error
checking. :p
import std.stdio;
import std.range;
R removeAt(R)(R range, size_t i)
{
auto rest = range.save;
rest.popFrontN(i + 1);
return range[0 .. i] ~ rest;
}
void main()
{
auto s = "neighbour";
assert(s.removeAt(7) == "neighbor");
}
Here is another one that uses the reduced range lazily:
import std.stdio;
import std.range;
import std.algorithm;
auto removeAt(R)(R range, size_t i)
{
auto rest = range.save;
rest.popFrontN(i + 1);
return [range[0 .. i], rest].chain.joiner;
}
void main()
{
auto s = "neighbour";
assert(s.removeAt(7).array == "neighbor");
}
Ali
More information about the Digitalmars-d-learn
mailing list