indexOf has startIndex but doesn't have limitIndex


#1

CharSequence.indexOf and friends can’t limit the range of the search.
This sucks a bit, could you please fix that with a sensible default parameter like, limitIndex:Int = length in those stdlib functions ?

real world use case : implementing a layout doing pagination for a TextView like widget for android : you want to know the index of the first ‘\n’ between position 1000 (start of a window) and say position 2000 (limit of a window) of your 100_000 chars long string (like when you want to split a paragraph inside a page into lines)
if you do indexOf(’\n’, 1000), in the case there is no ‘\n’, you’ll do a lot of useless work


#2

It’s interesting that in JDK there is an overload of indexOf with limit, but it isn’t exposed as public, so we’ll have to reimplement it from scratch if we would like to provide that overload.

As another approach could you create a CharSequence that provides a view over a region of the given CharSequence/String without copying and then use indexOf on that CharSequence?


#3

I can live with using a view of the region.
I can also use

(position until limit).firstOrNull { charSequence[it] == ‘\n’ } ?: -1

It’s just that I feel that if a function is in the standard library, it should do things the right way.
(especially since this method is supposed to be available on the jvm / the browser/ native

And for this use case, indexOf should be the right tool to do the job, but it isn’t.
So, It feels wrong.

Also, in this case, it is also nicer to return limit instead of -1.
If the cost of having more arguments, with defaults, is acceptable, I wonder if the signature couldn’t be : indexOf(startIndex:Int=0, limit:Int=charSequence.length, nothingFound:Int=-1)