n ocurrance in a string

BCS nothing at pathlink.com
Tue Jan 2 22:53:35 PST 2007


Heinz wrote:
> == Quote from BCS (nothing at pathlink.com)'s article
>> Heinz wrote:
>>> Hi,
>>>
>>> I'm doing a bit of work with strings. There's a function called find in
>>> std.string. This function returns the first ocurrance of a substring in a
>>> string, but how can i get the second, thrith, fifth...Nth ocurrance?
>>> Thanks a lot.
>> slice off the front:
>> char[] string = ...
>> int i = FindInString(string, "whatever");
>> i++;
>> i += FindInString(string[i..$], "whatever");
>> You may want to change this a bit for checking the return value (test of
>> no matche) and starting then next search more than one part the last (to
>> avoid overlapping matches.
> 
> Man, i found a bug in the method you suggest while trying to code it:
> 
> The returned int is no longer relative to beginning of the original string because
> every time you call this find function it takes a diferent string as parameter.
> Any other ideas?
> 
> Thx

That is why the second find use an += rather than a +, that way it walks 
i through the string.

finding "i" in

deikilihhgsdf

round 	find returns	i
1	2		3	(remember the i++)
2	1		5
3	1		7

It still might not work (I haven't tested it yet) but something along 
that line should.

As to the overhead cost, if you want to find each occurrence in order 
you wont want to put it in a function, just put it at the top of a loop. 
That shouldn't be much worse than optimum.


More information about the Digitalmars-d-learn mailing list