Home > Java > JavaBase > Java gets the first few characters of a string

Java gets the first few characters of a string

angryTom
Release: 2019-11-11 14:31:10
Original
15198 people have browsed it

Java gets the first few characters of a string

java takes the first few characters of a string

The String class in Java provides a substring (int from, int to) method is used to intercept the characters from the position from to to-1 in the string.

Because the character position of the string starts from 0, and the substring(int from, int to) method is closed in the front and open in the back, that is, [from, to), which can be understood as [from, to- 1].

At the same time, to can be omitted (polymorphism). By default, to intercepts the last digit of the string. (Recommended tutorial: java tutorial)

String str = "www.php.cn";
System.out.println(str.substring(0, 3)); // www
Copy after login

Also note that String in Java is an immutable type, so the substring() method does not change the original string, but A new string is returned.

System.out.println(str); // www.php.cn
Copy after login

The above is the detailed content of Java gets the first few characters of a string. 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