How to get a substring?

Damian damianday at hotmail.co.uk
Sat Oct 26 16:36:20 PDT 2013


On Saturday, 26 October 2013 at 23:19:56 UTC, Namespace wrote:
> On Saturday, 26 October 2013 at 22:17:33 UTC, Ali Çehreli wrote:
>> On 10/26/2013 02:25 PM, Namespace wrote:
>>> On Saturday, 26 October 2013 at 21:23:13 UTC, Gautam Goel 
>>> wrote:
>>>> Dumb Newbie Question: I've searched through the library 
>>>> reference, but
>>>> I haven't figured out how to extract a substring from a 
>>>> string. I'd
>>>> like something like string.substring("Hello", 0, 2) to 
>>>> return "Hel",
>>>> for example. What method am I looking for? Thanks!
>>>
>>> Use slices:
>>>
>>> string msg = "Hello";
>>> string sub = msg[0 .. 2];
>>
>> Yes but that works only if the string is known to contain only 
>> ASCII codes. (Otherwise, a string is a collection of UTF-8 
>> code units.)
>>
>> I could not find a subString() function either but it turns 
>> out to be trivial to implement with Phobos:
>>
>> import std.range;
>> import std.algorithm;
>>
>> auto subRange(R)(R s, size_t beg, size_t end)
>> {
>>    return s.dropExactly(beg).take(end - beg);
>> }
>>
>> unittest
>> {
>>    assert("abcçdef".subRange(2, 4).equal("cç"));
>> }
>>
>> void main()
>> {}
>>
>> That function produces a lazy range. To convert it eagerly to 
>> a string:
>>
>> import std.conv;
>>
>> string subString(string s, size_t beg, size_t end)
>> {
>>    return s.subRange(beg, end).text;
>> }
>>
>> unittest
>> {
>>    assert("Hello".subString(0, 2) == "He");
>> }
>>
>> Ali
>
> Yeah that is of course easier and nicer than C++... :D Just 
> kidding. I think the slice should be enough. This example would 
> have deterred me from further use if I had seen it it in my 
> beginning.

This functionality should really be provided in phobos str.string!
It is a very common function and I have also made the mistake of
slicing a range in the past :/


More information about the Digitalmars-d-learn mailing list