Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rightSplit() and second argoment for split() #9982

Open
dlangBugzillaToGithub opened this issue Jun 8, 2013 · 0 comments
Open

rightSplit() and second argoment for split() #9982

dlangBugzillaToGithub opened this issue Jun 8, 2013 · 0 comments

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2013-06-08T15:19:30Z

Transfered from https://issues.dlang.org/show_bug.cgi?id=10309

Description

If I have a string as "10,20,30" and I need to split it taking the part after the last comma and all before it, in Python I use rsplit() with optional argument 1:


>>> s = "10,20,30"
>>> a, b = s.rsplit(",", 1)
>>> assert a, b == "10,20", "30"


The optional second argument tells Python when to stop splitting, and the "r" suffix of split means "from the right":

>>> "10,20,30,40,50".rsplit(",", 2)
['10,20,30', '40', '50']
>>> "10,20,30,40,50".split(",", 2)
['10', '20', '30,40,50']


One (awkward) way to do the same thing in D+Phobos is:

import std.algorithm: find;
import std.range: retro;
void main() {
    auto s = "10,20,30";
    string a = s.retro.find(",").retro[0 .. $ - 1];
    string b = s[a.length + 1 .. $];
    assert (a == "10,20");
    assert(b == "30");
}



I don't see a rsplit or rSplit or rightSplit in std.string, but I see findSplitAfter and findSplitBefore in std.algorithm:

s.findSplitAfter(",")
==>
Tuple!(string, string)("10,", "20,30")

s.findSplitBefore(",")
==>
Tuple!(string, string)("10", ",20,30")


If I use std.range.retro:
s.retro.findSplitBefore(",")
==>
Tuple!(Result, Result)(03, ,02,01)

Also notice the lack of " inside the tuple, those aren't strings.

And indeed this is not accepted:
s.retro.findSplitBefore(",")[0].retro


If I am not missing something from Phobos, then maybe it's a good idea to add a rSplit(string,count=-1) (or rightSplit) to std.string or std.array (and maybe add a second argument to std.array.split as in Python).
@LightBender LightBender removed the P4 label Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants