If you are trying to get characters and substrings by index with in a String then charAt() and subString() methods respectively can be used.
- If you are looking for methods to compare string in java using methods like startsWith(), endsWith(), equals() etc.refer String comparison in Java
Using charAt() method
You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1.
As example– If you want to get the character at index 3 in a string:
String str = "Example String";
char resChar = str.charAt(3);
Using subString() method
If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions -
- String substring(int beginIndex, int endIndex) - Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1 which means beginIndex is inclusive where as endIndex is exclusive. IndexOutOfBoundsException is thrown if the beginIndex is negative, or endIndex is larger than the length of this String object, or sbeginIndex is larger than endIndex.
- String substring(int beginIndex) - Returns a new string that is a substring of this string. The integer argument specifies the index of the first character. Here, the returned substring extends to the end of the original string. IndexOutOfBoundsException is thrown if beginIndex is negative or larger than the length of this String object.
Example Code
public class SubStringDemo {
public static void main(String[] args) {
String str = "Example String";
System.out.println("Value - " + str.substring(0, 7));
System.out.println("Value - " + str.substring(8));
System.out.println("Value - " + str.substring(14));
}
}
Output
Value - Example
Value - String
Value -
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
E | x | a | m | p | l | e | S | t | r | i | n | g |
It’ll be easy to understand with the image, when subString method is called with indexes 0 and 7, returned subString would be “Example” which is index 0-6 as starting index is inclusive and endIndex is not inclusive.
Same way when subString method is called with startIndex as 8 then returned string would be from index 8 till end that’s why String is returned.
If subString() method is called with the length of the string (14 in this case) then empty space is returned. Passing any argument beyond that (more than 14) will result in IndexOutOfBoundsException.
That's all for this topic String charAt() and subString() methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related topics
You may also like -