Java 中常用的字符串函数
Java中有很多字符串函数,用于对字符串进行各种操作,例如字符串连接,截取,查找,替换,转换等等。下面列举一些常用的字符串函数。
1. length():获取字符串的长度
例如:
String str = "hello world"; int len = str.length(); System.out.println(len);
输出结果为:11
2. charAt(index):获取指定位置上的字符
例如:
String str = "hello world"; char ch = str.charAt(0); System.out.println(ch);
输出结果为:h
3. substring(startIndex, endIndex):截取字符串中指定范围内的子字符串
例如:
String str = "hello world"; String subStr = str.substring(0, 5); System.out.println(subStr);
输出结果为:hello
4. equals(str):判断两个字符串是否相等
例如:
String str1 = "hello"; String str2 = "world"; boolean flag = str1.equals(str2); System.out.println(flag);
输出结果为:false
5. equalsIgnoreCase(str):判断两个字符串是否相等(忽略大小写)
例如:
String str1 = "HELLO"; String str2 = "hello"; boolean flag = str1.equalsIgnoreCase(str2); System.out.println(flag);
输出结果为:true
6. indexOf(str):查找指定字符串在原字符串中首次出现的位置
例如:
String str = "hello world";
int index = str.indexOf("world");
System.out.println(index);
输出结果为:6
7. lastIndexOf(str):查找指定字符串在原字符串中最后一次出现的位置
例如:
String str = "hello world";
int index = str.lastIndexOf("o");
System.out.println(index);
输出结果为:7
8. replace(oldStr, newStr):将字符串中的指定串替换为新的串
例如:
String str = "hello world";
String newStr = str.replace("world", "java");
System.out.println(newStr);
输出结果为:hello java
9. split(str):将字符串按指定字符串分割成字符串数组
例如:
String str = "hello world java";
String[] arr = str.split(" ");
for (String s : arr) {
System.out.println(s);
}
输出结果为:
hello
world
java
10. toLowerCase():将字符串中的所有字符转换为小写字母
例如:
String str = "HELLO"; String lowerStr = str.toLowerCase(); System.out.println(lowerStr);
输出结果为:hello
11. toUpperCase():将字符串中的所有字符转换为大写字母
例如:
String str = "hello"; String upperStr = str.toUpperCase(); System.out.println(upperStr);
输出结果为:HELLO
12. trim():去除字符串首尾的空格
例如:
String str = " hello world "; String trimStr = str.trim(); System.out.println(trimStr);
输出结果为:hello world
13. startsWith(str):判断字符串是否以指定字符串开头
例如:
String str = "hello world";
boolean flag = str.startsWith("hello");
System.out.println(flag);
输出结果为:true
14. endsWith(str):判断字符串是否以指定字符串结尾
例如:
String str = "hello world";
boolean flag = str.endsWith("world");
System.out.println(flag);
输出结果为:true
15. valueOf(num):将数字转换成字符串
例如:
int num = 100; String str = String.valueOf(num); System.out.println(str);
输出结果为:100
总结:
以上是 Java 中常用的字符串函数,通过这些函数我们可以实现对字符串的各种操作,让字符串变得更加灵活和有用。在实际开发中,对于字符串的处理是经常用到的,因此熟练掌握这些函数对我们的工作具有非常重要的意义。
