The substring method in Java to intercept a string: [public String substring(int beginIndex)] starts from the index beginIndex and ends at the end of the entire string.
The substring method in Java to intercept a string:
1,public String substring(int beginIndex)
The string intercepted by this method starts from the index beginIndex and ends at the end of the entire string, for example: String String s = "abcdef";
Call s .substring(2) means intercepting from index 2 of the string to the end of the entire string. The intercepted string is cdef
2,public String substring(int beginIndex, int endIndex)
The string intercepted by this method starts from beginIndex and ends at endIndex - 1 of the string index. That is, the intercepted string does not include the characters corresponding to the endIndex index, so the maximum value of endIndex is the entire string. Length, so when using this method, you need to pay special attention to the problem of string interception and out-of-bounds problems.
The following is the specific code:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); System.out.println(s.substring(0, 2)); System.out.println(s.substring(2)); sc.close(); } }
Input from the console: saahdfasgfdga
Related learning recommendations:java basic tutorial
The above is the detailed content of How to intercept a string using substring in Java. For more information, please follow other related articles on the PHP Chinese website!