Why does Java use one past index for the upper bound in string operations?

In string functions like substring ()

"hello".substring(0, 3) 

returns hel
while index 0-3 includes hell

and in the method of the end of the cont () regular expression

 mat = Pattern.compile("test").matcher("test"); mat.find(); System.out.println(mat.end()); 

returns 4 whereas the first match ends with index 3

I'm just wondering why Java works this way

+5
source share
1 answer

First, since the endpoint is excluded, s.substring(i,j) has a length ji (which is intuitively correct).

For another, s.substring(i,j) + s.substring(j,k) is equal to s.substring(i,k) (for reasonable values ​​of i , j and k ).

In addition, s.substring(0, s.length()) describes all s as it should, because the endpoint is excluded.

If the endpoint was turned on, you constantly had to remember to add or subtract it from things to make the work work.

Matcher.end() is consistent with them: start-inclusive, end-exclusive, so s.substring(m.start(), m.end()) gives a substring.

+6
source

Source: https://habr.com/ru/post/1275807/


All Articles