How to retrieve a specific substring in a Java string?

In Java, you can use the substring method to obtain a specified substring of a string. This method has two overloaded versions.

  1. extract a portion of a string starting from a specific index
  2. extract a portion of the string, starting at the specified beginning index and ending at the specified ending index

Here is an example code:

String str = "Hello World";

// 从索引位置2开始截取子字符串
String substring1 = str.substring(2);
System.out.println(substring1); // 输出 "llo World"

// 从索引位置2开始,截取到索引位置6之前的子字符串
String substring2 = str.substring(2, 6);
System.out.println(substring2); // 输出 "llo "

Please note that index positions are counted starting from 0, so the index of the first character is 0.

广告
Closing in 10 seconds
bannerAds