How to get a substring using the String.substring() method in Java?
The String class in Java provides a very useful method substring(), which can be used to obtain the substring of a string. It allows us to select a portion of characters from a string and return it as a new string. This article will explain how to use the substring() method in Java and provide some code examples.
Using the substring() method is very simple. It has two overloaded forms:
The following is some sample code using the substring() method:
// Example 1: intercept the back part of the string
String str = "Hello World";
String subStr = str.substring(6);
System.out.println(subStr); // Output: World
// Example 2: Intercept part of the string
String str = "Hello World";
String subStr = str.substring(0, 5);
System.out.println(subStr); // Output: Hello
// Example 3: Get The last character of the string
String str = "Hello World";
String lastChar = str.substring(str.length() - 1);
System.out.println(lastChar); // Output: d
// Example 4: Extract the username part of the email address
String email = "example@example.com";
int atIndex = email.indexOf("@");
String username = email.substring(0, atIndex);
System.out.println(username); // Output: example
You need to pay attention to the following points when using the substring() method :
To sum up, the String.substring() method in Java is a very useful method that can be used to obtain the substring of a string. We can use it to intercept part of the string according to specific needs. Hopefully the code examples provided in this article will help you better understand and use the substring() method.
The above is the detailed content of How to get a substring using String.substring() method in Java?. For more information, please follow other related articles on the PHP Chinese website!