Home > Java > JavaBase > body text

How to intercept a string using substring in Java

coldplay.xixi
Release: 2020-10-29 16:19:47
Original
7304 people have browsed it

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();
}
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template