Java字符串函数:处理字符串的常用函数及其使用方法
发布时间:2023-06-09 05:14:25
Java字符串函数是Java中常用的一种数据类型,它提供了许多处理字符串的常用函数,可以帮助我们轻松地对字符串进行操作和处理。本文将介绍Java字符串函数的常用函数及其使用方法。
1. length()方法
该方法用于获取字符串的长度,即字符串中包含的字符数量。示例如下:
String str = "abcdefg"; int len = str.length(); System.out.println(len); // 输出结果为7
2. charAt()方法
该方法用于获取字符串中指定位置的字符,该位置从零开始。示例如下:
String str = "abcdefg"; char ch = str.charAt(2); System.out.println(ch); // 输出结果为 c
3. indexOf()方法
该方法用于获取指定字符或子串在字符串中第一次出现的位置,如果没有找到则返回-1。示例如下:
String str = "abcdefg";
int index = str.indexOf("e");
System.out.println(index); // 输出结果为4
4. substring()方法
该方法用于获取字符串中指定位置开始的子串,也可用于截取字符串。示例如下:
String str = "abcdefg"; String subStr = str.substring(2, 5); System.out.println(subStr); // 输出结果为cde
5. toUpperCase()方法
该方法用于将字符串中的所有字母转换为大写字母。示例如下:
String str = "abcdefg"; String upperStr = str.toUpperCase(); System.out.println(upperStr); // 输出结果为ABCDEFG
6. toLowerCase()方法
该方法用于将字符串中的所有字母转换为小写字母。示例如下:
String str = "ABCDEFG"; String lowerStr = str.toLowerCase(); System.out.println(lowerStr); // 输出结果为abcdefg
7. concat()方法
该方法用于将一个字符串连接到另一个字符串的末尾处。示例如下:
String str1 = "Hello "; String str2 = "world!"; String str3 = str1.concat(str2); System.out.println(str3); // 输出结果为Hello world!
8. replace()方法
该方法用于将指定的字符或子串在字符串中替换为另一个指定的字符或子串。示例如下:
String str = "aabbcc";
String newStr = str.replace("b", "d");
System.out.println(newStr); // 输出结果为aaddcc
9. trim()方法
该方法用于去掉字符串中的首尾空格。示例如下:
String str = " Hello world! "; String newStr = str.trim(); System.out.println(newStr); // 输出结果为Hello world!
10. split()方法
该方法用于将字符串按指定的分隔符分割成多个子串,并将所有子串存储在一个数组中。示例如下:
String str = "a,b,c,d,e";
String[] arr = str.split(",");
for (String s : arr) {
System.out.println(s);
}
// 输出结果为:
// a
// b
// c
// d
// e
以上就是Java字符串函数的常用函数及其使用方法。这些函数可以帮助我们更轻松地对字符串进行操作和处理。使用这些函数可以帮助我们提高编程效率,减少代码量。
