Re: Is there a string remove method, that takes an index

2013-01-30 Thread FG

On 2013-01-30 04:27, Ali Çehreli wrote:

 s = s[0..7] ~ s[8..$];


As with the other slicing approaches, it would be best to check first if 
s.length = i (with i = 8 in this case).




Re: Is there a string remove method, that takes an index

2013-01-29 Thread Ali Çehreli

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