How to get a substring?

Nicolas Sicard dransic at gmail.com
Sat Oct 26 18:24:34 PDT 2013


On Sunday, 27 October 2013 at 00:18:41 UTC, Timothee Cour wrote:
> 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));
> }
>

Another one, with negative index like Javascript's String.slice():
http://dpaste.dzfl.pl/608435c5


More information about the Digitalmars-d-learn mailing list