How to extract substring in Java?
In Java, you can use the substring method of the String class to extract a portion of a string. This method has two overloaded versions.
- substring(int beginIndex): Extracts a substring from the starting index to the end of the string.
- substring(int beginIndex, int endIndex): Extracts a substring starting from beginIndex up to endIndex-1.
The code example is shown below:
String str = "Hello World";
String sub1 = str.substring(6); // 截取从索引 6 开始到末尾的子字符串,结果为 "World"
String sub2 = str.substring(0, 5); // 截取从索引 0 开始到索引 4 的子字符串,结果为 "Hello"
System.out.println(sub1);
System.out.println(sub2);
The result output is:
World
Hello