Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring index range

Code:

public class Test {     public static void main(String[] args) {         String str = "University";         System.out.println(str.substring(4, 7));     }    } 

Output: ers

I do not really understand how the substring method works. Does the index start at 0? If I start with 0, e is at index 4 but char i is at 7 so the output would be ersi.

like image 216
UpCat Avatar asked Dec 31 '10 12:12

UpCat


People also ask

What is the index range of string?

Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. first and last may be specified as for the index method.

How do you select a range of a string?

Using String.substring() method. You can supply both a start and an end index, or just a start index. When using both a start index and an end index, you get that section of string — the substring — including the character at the start index, but not the character at the end index. For example, "hello".

Does substring include last index?

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

How do you find the index of a substring?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.


1 Answers

0: U

1: n

2: i

3: v

4: e

5: r

6: s

7: i

8: t

9: y

Start index is inclusive

End index is exclusive

Javadoc link

like image 193
Axel Fontaine Avatar answered Sep 28 '22 03:09

Axel Fontaine