常用方法
Java中的String
类提供了一系列方法来操作和查询字符串。以下是一些常用的String
类方法及其功能:
char charAt(int index)
: 返回字符串中指定索引位置的字符。int compareTo(String anotherString)
: 将当前字符串与另一个字符串进行比较。如果两者相等,返回0;如果不等,返回第一个不相同的字符的ASCII码值的差值。String concat(String str)
: 将当前字符串与另一个字符串拼接。byte[] getBytes()
: 将字符串转换为字节数组。char[] toCharArray()
: 将字符串转换为字符数组。int hashCode()
: 返回字符串的哈希码值。int indexOf(int ch)
: 返回字符串中某个字符首次出现的索引。int indexOf(String str)
: 返回字符串中某个子串首次出现的索引。int lastIndexOf(int ch)
: 返回字符串中某个字符最后一次出现的索引。int lastIndexOf(String str)
: 返回字符串中某个子串最后一次出现的索引。String toLowerCase()
: 将字符串转换为全小写形式。String toUpperCase()
: 将字符串转换为全大写形式。String valueOf(float f)
: 将浮点数转换为字符串。String valueOf(int i)
: 将整数转换为字符串。String[] split(String regex)
: 根据正则表达式分割字符串,并返回字符串数组。
这些方法使得String
类成为Java中处理字符串的强大工具。在实际编程中,可以根据需要选择合适的方法来进行字符串操作。
案例
public class ComprehensiveStringMethodsDemo {
public static void main(String[] args) {
// 原始字符串
String originalString = "Hello, World! Java is fun. Java2Script, Java3D.";
// 1. charAt()
System.out.println("第一个字符: " + originalString.charAt(0));
// 2. compareTo()
String comparedString = "Hello, World!";
System.out.println("与另一个字符串比较: " + originalString.compareTo(comparedString));
// 3. concat()
String appendedString = originalString.concat(" Welcome to Java.");
System.out.println("拼接后的字符串: " + appendedString);
// 4. getBytes()
byte[] bytes = originalString.getBytes();
System.out.println("字节数组长度: " + bytes.length);
// 5. toCharArray()
char[] chars = originalString.toCharArray();
System.out.println("字符数组长度: " + chars.length);
// 6. hashCode()
System.out.println("字符串哈希码: " + originalString.hashCode());
// 7. indexOf()
System.out.println("'Java'第一次出现的索引: " + originalString.indexOf("Java"));
// 8. lastIndexOf()
System.out.println("'a'最后一次出现的索引: " + originalString.lastIndexOf('a'));
// 9. toLowerCase()
String lowerCaseString = originalString.toLowerCase();
System.out.println("全小写字符串: " + lowerCaseString);
// 10. toUpperCase()
String upperCaseString = originalString.toUpperCase();
System.out.println("全大写字符串: " + upperCaseString);
// 11. valueOf()
float floatValue = 3.14f;
int intValue = 12345;
System.out.println("浮点数转换为字符串: " + String.valueOf(floatValue));
System.out.println("整数转换为字符串: " + String.valueOf(intValue));
// 12. split()
String[] words = originalString.split("\\s+|,\\s*|\\.\\s*");
System.out.println("分割后的单词数组长度: " + words.length);
for (String word : words) {
System.out.println("单词: " + word);
}
}
}