Java字符串函数(StringFunction)完整使用指南
Java有很多字符串函数可供使用。这里是一份完整的指南,介绍了Java中经常使用的字符串函数及其用法。
一、String类中的常用字符串函数:
1. length()
返回字符串的长度。
例如:
String s = "hello"; System.out.println(s.length()); //输出 5
2. charAt(int index)
返回字符串中指定索引位置的字符。
例如:
String s = "hello"; System.out.println(s.charAt(1)); //输出 e
3. substring(int beginIndex, int endIndex)
返回字符串中指定区间的子串。
例如:
String s = "hello"; System.out.println(s.substring(1, 3)); //输出 el
4. indexOf(String str)
返回字符串中 次出现指定字符串的索引位置,如果没有找到则返回 -1。
例如:
String s = "hello";
System.out.println(s.indexOf("l")); //输出 2
5. replace(char oldChar, char newChar)
返回一个新字符串,用指定字符替换原字符串中的指定字符。
例如:
String s = "hello";
System.out.println(s.replace('l', 'p')); //输出 heppo
6. toUpperCase()
将字符串中的所有字符都转换为大写。
例如:
String s = "hello"; System.out.println(s.toUpperCase()); //输出 HELLO
7. toLowerCase()
将字符串中的所有字符都转换为小写。
例如:
String s = "HELLO"; System.out.println(s.toLowerCase()); //输出 hello
二、使用正则表达式的字符串函数:
1. matches(String regex)
判断当前字符串是否符合指定的正则表达式。
例如:
String s = "hello";
System.out.println(s.matches("he.*o")); //输出 true
2. split(String regex)
根据指定的正则表达式分割字符串,并返回一个字符串数组。
例如:
String s = "hello,world";
String[] arr = s.split(",");
for (String str : arr) {
System.out.println(str);
}
输出:
hello world
3. replaceAll(String regex, String replacement)
使用替换字符串替换匹配指定正则表达式的字符串。
例如:
String s = "hello,world";
System.out.println(s.replaceAll(",", "-")); //输出 hello-world
三、StringBuilder类中的字符串函数:
StringBuilder类可以动态修改字符串,具有很多实用的字符串处理函数。
1. append(String str)
将指定字符串追加到当前字符串对象的末尾。
例如:
StringBuilder sb = new StringBuilder("hello");
sb.append(",world");
System.out.println(sb.toString()); //输出 hello,world
2. insert(int offset, String str)
在指定索引位置插入指定字符串。
例如:
StringBuilder sb = new StringBuilder("hello");
sb.insert(1, "x");
System.out.println(sb.toString()); //输出 hxello
3. delete(int startIndex, int endIndex)
删除指定区间的字符。
例如:
StringBuilder sb = new StringBuilder("hello");
sb.delete(1, 3);
System.out.println(sb.toString()); //输出 hlo
4. replace(int startIndex, int endIndex, String str)
替换指定区间的字符。
例如:
StringBuilder sb = new StringBuilder("hello");
sb.replace(1, 3, "pp");
System.out.println(sb.toString()); //输出 helloworld
四、使用正则表达式的StringBuilder函数:
StringBuilder类也可以使用正则表达式处理字符串。
1. replaceAll(String regex, String replacement)
使用替换字符串替换匹配指定正则表达式的字符串。
例如:
StringBuilder sb = new StringBuilder("hello,world");
System.out.println(sb.toString().replaceAll(",", "-")); //输出 hello-world
以上就是Java中常见的字符串函数,可以用于字符串的处理和操作。熟练掌握这些函数可以让我们的Java程序更加高效、简洁。
