10个Java函数快速处理字符串
Java中有很多处理字符串的函数,这些函数可以帮助我们快速处理字符串操作,提高代码效率。下面列出了一些常用的Java函数,希望对大家有帮助。
1. split()函数
split()函数可以将String类型的字符串按照指定的分隔符分割成String类型的数组,例如:
String str = "hello,world";
String[] arr = str.split(",");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
输出结果为:
hello
world
2. replace()函数
replace()函数可以将String类型的字符串中指定的字符或字符序列替换成另一个字符或字符序列,例如:
String str = "hello world";
String newStr = str.replace("world", "java");
System.out.println(newStr);
输出结果为:
hello java
3. substring()函数
substring()函数可以返回String类型的字符串中的一个子字符串,这个子字符串是由指定的开始位置和结束位置之间的字符组成的,例如:
String str = "hello world";
String substr = str.substring(6, 10);
System.out.println(substr);
输出结果为:
worl
4. trim()函数
trim()函数可以返回String类型的字符串中将首尾空格去除后的新字符串,例如:
String str = " hello world ";
String newStr = str.trim();
System.out.println(newStr);
输出结果为:
hello world
5. length()函数
length()函数可以返回String类型的字符串的长度,即字符串中字符的个数,例如:
String str = "hello world";
int len = str.length();
System.out.println(len);
输出结果为:
11
6. indexOf()函数
indexOf()函数可以返回String类型的字符串中查找到的指定字符或字符序列 次出现的位置,如果未找到则返回-1,例如:
String str = "hello world";
int index = str.indexOf("world");
System.out.println(index);
输出结果为:
6
7. startsWith()函数
startsWith()函数可以判断String类型的字符串是否以指定的字符或字符序列开始,例如:
String str = "hello world";
boolean isStartsWith = str.startsWith("hello");
System.out.println(isStartsWith);
输出结果为:
true
8. endsWith()函数
endsWith()函数可以判断String类型的字符串是否以指定的字符或字符序列结束,例如:
String str = "hello world";
boolean isEndsWith = str.endsWith("world");
System.out.println(isEndsWith);
输出结果为:
true
9. toLowerCase()函数
toLowerCase()函数可以将String类型的字符串中所有的大写字母转换成小写字母,例如:
String str = "Hello World";
String newStr = str.toLowerCase();
System.out.println(newStr);
输出结果为:
hello world
10. toUpperCase()函数
toUpperCase()函数可以将String类型的字符串中所有的小写字母转换成大写字母,例如:
String str = "Hello World";
String newStr = str.toUpperCase();
System.out.println(newStr);
输出结果为:
HELLO WORLD
以上是10个常用的Java函数,它们可以帮助我们快速处理字符串操作,提高代码效率。希望对大家有所帮助。
