How to get a substring?

Timothee Cour thelastmammoth at gmail.com
Sat Oct 26 17:18:25 PDT 2013


I've posted a while back a string=>string substring function that doesn't
allocating: google
"nonallocating unicode string manipulations"

code:

auto slice(T)(T a,size_t u, size_t v)if(is(T==string)){//TODO:generalize to
isSomeString
import std.exception;
auto m=a.length;
size_t i;
enforce(u<=v);
import std.utf;
while(u-- && i<m){
auto si=stride(a,i);
i+=si;
v--;
}
// assert(u==-1);
// enforce(u==-1);
size_t i2=i;
while(v-- && i2<m){
auto si=stride(a,i2);
i2+=si;
}
// assert(v==-1);
enforce(v==-1);
return a[i..i2];
}
unittest{
import std.range;
auto a="≈açç√ef";
auto b=a.slice(2,6);
assert(a.slice(2,6)=="çç√e");
assert(a.slice(2,6).ptr==a.slice(2,3).ptr);
assert(a.slice(0,a.walkLength) is a);
import std.exception;
assertThrown(a.slice(2,8));
assertThrown(a.slice(2,1));
}


On Sat, Oct 26, 2013 at 3:17 PM, Ali Çehreli <acehreli at yahoo.com> 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
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20131026/5debe6c0/attachment-0001.html>


More information about the Digitalmars-d-learn mailing list