How to get a substring?

Nicolas Sicard dransic at gmail.com
Sun Oct 27 00:13:09 PDT 2013


On Sunday, 27 October 2013 at 03:45:50 UTC, Timothee Cour wrote:
> On Sat, Oct 26, 2013 at 6:24 PM, Nicolas Sicard 
> <dransic at gmail.com> wrote:
>
>> 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
>>
>
> not as efficient as what I proposed since it's iterating over 
> the string
> twice (the 2nd index redoes the work done by 1st index). Could 
> be adapted
> though.

Yes. slice was a quick addition to before/after.

I also wonder if std.uni.graphemeStride would be more appropriate.


More information about the Digitalmars-d-learn mailing list