How to get a substring?

Ali Çehreli acehreli at yahoo.com
Sat Oct 26 15:17:33 PDT 2013


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



More information about the Digitalmars-d-learn mailing list