Java中可用的字符串处理函数有哪些?如何使用?
Java中可用的字符串处理函数较多,本文将列举一些常用的函数及其用法。
1. length():用于获取字符串的长度,返回值为int类型。
使用方法:String str = "hello world"; int len = str.length();
2. charAt():用于获取指定位置上的字符,返回值为char类型。
使用方法:String str = "hello"; char c = str.charAt(1); // 返回 'e'
3. concat():用于将两个字符串拼接在一起,返回值为拼接后的字符串。
使用方法:String str1 = "hello"; String str2 = "world"; String str3 = str1.concat(str2); // 返回 "helloworld"
4. toUpperCase():用于将字符串转换为大写字母形式。
使用方法:String str = "hello"; String upperStr = str.toUpperCase(); // 返回 "HELLO"
5. toLowerCase():用于将字符串转换为小写字母形式。
使用方法:String str = "HELLO"; String lowerStr = str.toLowerCase(); // 返回 "hello"
6. trim():用于去除字符串两端的空格。
使用方法:String str = " hello world "; String trimStr = str.trim(); // 返回 "hello world"
7. substring():用于获取字符串的子串,从指定位置开始,指定长度的字符。
使用方法:String str = "hello world"; String subStr = str.substring(3, 7); // 返回 "lo w"
8. indexOf():用于查找字符串中某个子字符串的位置。
使用方法:String str = "hello world"; int index = str.indexOf("world"); // 返回 6
9. replace():用于将字符串中某个子字符串替换为另一个字符串。
使用方法:String str = "hello world"; String replaceStr = str.replace("world", "java"); // 返回 "hello java"
10. split():用于将一个字符串按照指定的分隔符分割成多个子串。
使用方法:String str = "hello,world,java"; String[] arr = str.split(","); // 返回 ["hello", "world", "java"]
11. startsWith():用于判断一个字符串是否以指定子字符串开头。
使用方法:String str = "hello world"; boolean startsWithHello = str.startsWith("hello"); // 返回 true
12. endsWith():用于判断一个字符串是否以指定子字符串结尾。
使用方法:String str = "hello world"; boolean endsWithWorld = str.endsWith("world"); // 返回 true
13. compareTo():用于比较两个字符串的大小关系,返回值为int类型。
使用方法:String str1 = "apple"; String str2 = "banana"; int result = str1.compareTo(str2); // 返回 -1
以上是Java中常用的字符串处理函数及其用法,除此之外还有许多其他的字符串处理函数。掌握这些函数可以帮助我们更加方便和高效地处理字符串。
