了解Java中的字符串操作函数
发布时间:2023-12-04 07:32:02
Java中的字符串操作函数是指用来处理字符串的方法,可以实现字符串的拼接、截取、替换、比较、查找等功能。以下是Java中常用的字符串操作函数及其使用例子:
1. 字符串长度获取函数:length()
用于获取字符串的长度。
Example:
String str = "Hello World"; int length = str.length(); System.out.println(length); // 输出结果为 11
2. 字符串拼接函数:concat()
用于将一个字符串拼接到当前字符串的末尾。
Example:
String str1 = "Hello"; String str2 = "World"; String result = str1.concat(str2); System.out.println(result); // 输出结果为 "HelloWorld"
3. 字符串替换函数:replace()
用于将字符串中的某个字符或子串替换成指定的字符或子串。
Example:
String str = "Hello World";
String result = str.replace("World", "Java");
System.out.println(result); // 输出结果为 "Hello Java"
4. 字符串截取函数:substring()
用于从原字符串中截取指定索引范围内的子串。
Example:
String str = "Hello World"; String result = str.substring(6, 11); System.out.println(result); // 输出结果为 "World"
5. 字符串分割函数:split()
用于将字符串按指定的分隔符拆分成字符串数组。
Example:
String str = "Hello,World";
String[] result = str.split(",");
System.out.println(result[0]); // 输出结果为 "Hello"
System.out.println(result[1]); // 输出结果为 "World"
6. 字符串转换函数:toLowerCase() 和 toUpperCase()
分别用于将字符串中的所有字符转换为小写和大写。
Example:
String str = "Hello World"; String result1 = str.toLowerCase(); String result2 = str.toUpperCase(); System.out.println(result1); // 输出结果为 "hello world" System.out.println(result2); // 输出结果为 "HELLO WORLD"
7. 字符串比较函数:equals() 和 equalsIgnoreCase()
分别用于比较字符串是否相等和忽略大小写进行比较。
Example:
String str1 = "Hello"; String str2 = "hello"; boolean result1 = str1.equals(str2); boolean result2 = str1.equalsIgnoreCase(str2); System.out.println(result1); // 输出结果为 false System.out.println(result2); // 输出结果为 true
8. 字符串查找函数:indexOf() 和 lastIndexOf()
分别用于查找字符或子串在字符串中首次出现和最后一次出现的位置。
Example:
String str = "Hello World";
int result1 = str.indexOf("o");
int result2 = str.lastIndexOf("o");
System.out.println(result1); // 输出结果为 4
System.out.println(result2); // 输出结果为 7
以上只是Java中常见的字符串操作函数及其使用例子,Java还提供了其他丰富的字符串操作函数,如字符串比较、字符串格式化、字符串转换等。在实际开发中,根据具体需求选择合适的字符串操作函数可以提高编程效率。
