digitalmars.D.learn - Is there a string remove method, that takes an index
- Damian (7/7) Jan 29 2013 public string remove(string str, size_t start, size_t n) { }
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (44/48) Jan 29 2013 Yes but it's extremely simple with a huge warning sign on it: :)
- FG (3/4) Jan 30 2013 As with the other slicing approaches, it would be best to check first if...
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? Thank you.
Jan 29 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 suitablefor 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
Jan 29 2013
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).
Jan 30 2013