Home  >  Article  >  Java  >  How to intercept a string using substring in Java

How to intercept a string using substring in Java

coldplay.xixi
coldplay.xixiOriginal
2020-10-28 11:19:437294browse

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.

How to intercept a string using substring in Java

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

How to intercept a string using substring in Java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn