-
length(): Returns the length of the string.
String str = "Hello"; int length = str.length(); // length的值为5
-
charAt(int index): Returns the character at the specified index position in the string.
String str = "Hello"; char ch = str.charAt(1); // ch的值为'e'
-
substring(int beginIndex) and substring(int beginIndex, int endIndex): Returns the substring from the specified index to the end.
String str = "Hello World"; String substr1 = str.substring(6); // substr1的值为"World" String substr2 = str.substring(0, 5); // substr2的值为"Hello"
-
equals(Object obj): compares whether the string is equal to the specified object.
String str1 = "Hello"; String str2 = "World"; boolean isEqual = str1.equals(str2); // isEqual的值为false
-
compareTo(String anotherString): Compares two strings lexicographically. A return value of 0 means equal, a positive number means the current string is greater than the parameter string, and a negative number means the current string is smaller than the parameter string.
String str1 = "Apple"; String str2 = "Banana"; int result = str1.compareTo(str2); // result的值为-1
-
toUpperCase() and toLowerCase(): Convert a string to uppercase or lowercase.
String str = "Hello"; String upperCase = str.toUpperCase(); // upperCase的值为"HELLO" String lowerCase = str.toLowerCase(); // lowerCase的值为"hello"
-
contains(CharSequence sequence): Determines whether the string contains the specified character sequence.
String str = "Hello World"; boolean contains = str.contains("World"); // contains的值为true
-
replace(CharSequence target, CharSequence replacement): Replaces the specified character sequence in the string with a new character sequence.
String str = "Hello World"; String replaced = str.replace("World", "Java"); // replaced的值为"Hello Java"
-
split() method to split a string: it accepts a regular expression as an argument and splits the string into an array of substrings
String str = "Hello,World,Java"; String[] parts = str.split(","); // 使用逗号分割字符串 // parts数组的值为 ["Hello", "World", "Java"]
The split() method accepts a regular expression as an argument. If you want to use special characters for splitting, you need to escape them. For example, if you want to split with a period ".", you need to use "." as the delimiter.
String str = "Hello.World.Java"; String[] parts = str.split("\\."); // 使用句点分割字符串 // parts数组的值为 ["Hello", "World", "Java"]
Common methods in String
Guess you like
Origin blog.csdn.net/qq_44113347/article/details/131495112
Ranking