std.string.indexOf with an optional start-at parameter?

Aleksandar Ružičić ruzicic.aleksandar at gmail.com
Sun Apr 3 11:14:08 PDT 2011


I thought first of slicing, but isn't that making a copy of string?
And also, if I'm not mistaken if you slice out of range bounds (i.e.
haystack[5..$] when haystack.length < 5) you'll get exception, right?

That's why I think this would be nice to have feature, so you don't
have to worry if start position is within the string bounds, and you
won't need to write this:

> auto pos = indexOf(haystack[$-5..$], '$') + haystack.length-5;

when you want to start search from the end (since it's somehow less
readable than indexOf(haystack, '$', -5)).

On Sun, Apr 3, 2011 at 7:55 PM, Robert Jacques <sandford at jhu.edu> wrote:
> On Sun, 03 Apr 2011 13:39:40 -0400, Aleksandar Ružičić
> <ruzicic.aleksandar at gmail.com> wrote:
>
>> I needed std.string.indexOf to accept start position in the string to
>> start the search at. I was really surprised when I realized that this
>> (to me) standard parameter is "missing" (I'm used to indexOf in
>> javascript, strpos in php and equivalent methods in other languages,
>> which support start offset parameter).
>>
>> There might be some other function (in some other module) that does
>> what I want but I wasn't able to find it (I find D's documentation not
>> easy to search and read), so I've copied indexOf to my module and
>> added wanted functionality:
>>
>> https://gist.github.com/900589
>>
>> now, I'm able to write, for example:
>>
>> auto pos = indexOf(haystack, '$', 10); // will starts search at 11th
>> char in haystack
>
> auto pos = indexOf(haystack[10..$], '$') + 10;
>
>> and
>>
>> auto pos = indexOf(haystack, '$', -5); // will starts search at 5th
>> char from the end
>
> auto pos = indexOf(haystack[$-5..$], '$') + haystack.length-5;
>
>> My question is: is there a reason why there is no this functionality
>> in phobos (maybe there's some language feature I'm not aware of?) and
>> if no such reason exists, would it be possible to add it in future
>> version of phobos/dmd?
>
> Yes, the language feature is called slicing. See above. Also, you may want
> to look at the various find methods in std.algorithm. Generally, it's better
> to work with ranges/slices than indexes due to UTF's encoding scheme.
>


More information about the Digitalmars-d mailing list