counting the empty substring in a string results in infinite loop #8919
This example will never terminate:
import strutils proc test(s, sub: string): int = count(s, sub) echo test("hello world", "")
Since Nim allows the replacement of the empty substring, it would be probably reasonable to return the number of replacements that would be performed by
The text was updated successfully, but these errors were encountered:
Counting the empty string is not an API misuse as someone else claims. But raising an exception is better than looping infinitely.
In some circles the empty string is considered as the identity operator of string concatenation. From this point of view it makes sense to allow the replacement of the empty string and therefore to count the occurrences of such replacements.
But currently it would be more important to fix the handling of the empty string (aka zero-length match) in re.nim where in some cases it also ends in infinite loops.
It is an API misuse and the fact that it needs special code logic everywhere suggests that the view "the empty string is the identity operator of string concatenation" is just misguided. This is multiplication written with
proc mul(a, b: Natural): Natural = result = 0 for i in 1..b: result += a
Notice how the code naturally handles the
The messages produced about the API misuse could be better:
echo count("", "")
and the similar
A line-break before the first "`" instead of after it, would be better.
An explicit message such as "counting the empty string is an API misuse" or something similar would be helpful for logically impaired people like me.
Two other observations about the empty string:
I was expecting to get -1 when searching outside of the bounds of "somestring" (like for every other substring).