Java中的String类是用来表示字符串的类。它是一个不可变类,也就是说一旦字符串被创建,就不能被修改。
以下是String类中常用的方法:
-
length():返回字符串的长度。
String str = "Hello"; int length = str.length(); System.out.println(length); // Output: 5
-
charAt(int index):返回指定位置 index 处的字符。
String str = "Hello"; char ch = str.charAt(1); System.out.println(ch); // Output: e
-
contains(CharSequence sequence):判断字符串是否包含指定的字符序列。
String str = "Hello, world!"; boolean contains = str.contains("world"); System.out.println(contains); // 输出:true
-
concat(String str):将指定的字符串 str 连接到此字符串的末尾。
String str1 = "Hello"; String str2 = "World"; String result = str1.concat(str2); System.out.println(result); // Output: HelloWorld
-
equals(Object anObject):比较此字符串与指定的对象是否相等。
String str1 = "Hello"; String str2 = "Hello"; boolean isEqual = str1.equals(str2); System.out.println(isEqual); // Output: true
-
isEmpty():判断字符串是否为空。
String str = ""; boolean isEmpty = str.isEmpty(); System.out.println(isEmpty); // Output: true
-
indexOf(String str):返回指定字符串 str 在此字符串中第一次出现的位置。
String str = "Hello World"; int index = str.indexOf("World"); System.out.println(index); // Output: 6
-
substring(int beginIndex):返回一个新字符串,它是此字符串的一个子字符串。
String str = "Hello World"; String subStr = str.substring(6); System.out.println(subStr); // Output: World
-
toLowerCase():将字符串转换为小写。
String str = "Hello"; String lowerCaseStr = str.toLowerCase(); System.out.println(lowerCaseStr); // Output: hello
-
toUpperCase():将字符串转换为大写。
String str = "Hello"; String upperCaseStr = str.toUpperCase(); System.out.println(upperCaseStr); // Output: HELLO
-
trim():去除字符串两端的空格。
String str = " Hello "; String trimmedStr = str.trim(); System.out.println(trimmedStr); // Output: Hello
-
split(String regex):将字符串分割为字符串数组。
String str = "Hello,World"; String[] strArray = str.split(","); System.out.println(strArray[0]); // Output: Hello System.out.println(strArray[1]); // Output: World
-
startsWith(String prefix):测试此字符串是否以指定的前缀开始。
String str = "Hello World"; boolean startsWithHello = str.startsWith("Hello"); System.out.println(startsWithHello); // Output: true
-
endsWith(String suffix):测试此字符串是否以指定的后缀结束。
String str = "Hello World"; boolean endsWithWorld = str.endsWith("World"); System.out.println(endsWithWorld); // Output: true
-
replace(char oldChar, char newChar):返回一个新字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 来创建的。
String str = "Hello"; String replacedStr = str.replace('l', 'L'); System.out.println(replacedStr); // Output: HeLLo
-
compareTo(String anotherString):按字典顺序比较两个字符串。
String str1 = "Hello"; String str2 = "World"; int result = str1.compareTo(str2); System.out.println(result); // Output: -15
这些方法只是String类中的一小部分常用方法,还有其他很多方法可以用于字符串的处理。这些方法可以帮助我们在Java程序中对字符串进行各种操作和处理。