faster splitter

Patrick Schluter via Digitalmars-d digitalmars-d at puremagic.com
Fri May 27 11:34:25 PDT 2016


On Friday, 27 May 2016 at 14:41:29 UTC, Chris wrote:
> On Friday, 27 May 2016 at 14:06:09 UTC, Chris wrote:
>>
>> This outperforms both `manual_find` and the improved `std find`
>>
>> string findStringS_Manual(string haystack, string needle)
>> {
>> 	
>> 	if (needle.length > haystack.length)
>> 		return haystack[$..$];
>> 	outer:
>> 	for (auto i = 0; i < haystack.length; i++)
>> 	{
>> 		if (haystack[i] != needle[0])
>> 			continue;
>> 		for (size_t j = i+1, k = 1; k < needle.length; ++j, ++k)
>> 			if (haystack[j] != needle[k])
>> 			continue outer;
>> 		return haystack[i..$];
>> 	}
>> 	return haystack[$..$];
>> }
>>
>
> Little bug fix:
>
> for (size_t j = (i+1 < haystack.length) ? i+1 : i, k = 1; k < 
> needle.length; ++j, ++k)
>

The upper bound of the outer loop should be 
haystack.length-needle.length. There's no point in searching 
after that point as the needle would not fit anymore and it 
avoids the buffer overrun you have in your code when the first 
character of the needle is found after that point.
You can also remove then your ?: test in the j loop as that case 
is handled automatically then.


More information about the Digitalmars-d mailing list