Issue 10309 - rightSplit() and second argoment for split()
Summary: rightSplit() and second argoment for split()
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-06-08 15:19 UTC by bearophile_hugs
Modified: 2024-12-01 16:17 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2013-06-08 15:19:30 UTC
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).
Comment 1 dlangBugzillaToGithub 2024-12-01 16:17:54 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/9982

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB