String类是Java中最常用的类之一,它提供了许多方法来操作字符串。以下是一些常用的String类方法及其代码示例:
length():返回字符串的长度。
String str = "Hello World";
int length = str.length();
System.out.println("Length: " + length); // 输出:Length: 11
charAt(int index):返回指定索引处的字符。
String str = "Hello World";
char ch = str.charAt(4);
System.out.println("Character at index 4: " + ch); // 输出:Character at index 4: o
substring(int beginIndex, int endIndex):返回一个新字符串,它是此字符串的一个子字符串。
String str = "Hello World";
String subStr = str.substring(6, 11);
System.out.println("Substring from index 6 to 10: " + subStr); // 输出:Substring from index 6 to 10: World
indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引。
String str = "Hello World";
int index = str.indexOf("World");
System.out.println("Index of 'World': " + index); // 输出:Index of 'World': 6
lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引。
String str = "Hello World World";
int lastIndex = str.lastIndexOf("World");
System.out.println("Last index of 'World': " + lastIndex); // 输出:Last index of 'World': 12
equals(Object obj):比较两个字符串的内容是否相等。
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2);
System.out.println("Are the strings equal? " + isEqual); // 输出:Are the strings equal? true
compareTo(String anotherString):按字典顺序比较两个字符串。
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
if (result < 0) {
System.out.println(str1 + " comes before " + str2); // 输出:apple comes before banana
} else if (result > 0) {
System.out.println(str1 + " comes after " + str2); // 输出:apple comes after banana
} else {
System.out.println(str1 + " is equal to " + str2); // 输出:apple is equal to apple
}
toLowerCase():将所有字符转换为小写。
String str = "Hello World";
String lowerStr = str.toLowerCase();
System.out.println("Lowercase string: " + lowerStr); // 输出:Lowercase string: hello world
toUpperCase():将所有字符转换为大写。
String str = "Hello World";
String upperStr = str.toUpperCase();
System.out.println("Uppercase string: " + upperStr); // 输出:Uppercase string: HELLO WORLD
trim():去除字符串两端的空格。
String str = " Hello World ";
String trimmedStr = str.trim();
System.out.println("Trimmed string: " + trimmedStr); // 输出:Trimmed string: Hello World