Java中如何实现基本的字符处理函数
发布时间:2023-06-04 11:39:15
Java中提供了丰富的字符串处理函数,如长度、子串、连接、比较、替换、格式化、转换大小写等。下面分别介绍这些函数的使用方法。
1. 长度函数
字符串长度函数length()返回字符串的长度,例如:
String str = "hello world";
int len = str.length();
System.out.println("字符串长度为:" + len);
输出结果为:
字符串长度为:11
2. 子串函数
字符串子串函数substring()返回指定索引范围内的子串。其中一个参数是起始索引,另一个参数是可选的结束索引,如果没有指定结束索引,则将从起始索引开始截取至字符串末尾。例如:
String str = "hello world";
String substr = str.substring(1, 4);
System.out.println("截取的子串为:" + substr);
输出结果为:
截取的子串为:ell
3. 连接函数
字符串连接函数concat()将两个字符串连接成一个字符串,例如:
String str1 = "hello";
String str2 = "world";
String str3 = str1.concat(str2);
System.out.println("连接后的字符串为:" + str3);
输出结果为:
连接后的字符串为:helloworld
4. 比较函数
字符串比较函数compareTo()对两个字符串进行字典序比较,返回一个整数。如果字符串相等,则返回0;如果当前字符串小于另一个字符串,则返回小于0的整数;否则返回大于0的整数。例如:
String str1 = "hello";
String str2 = "world";
int result = str1.compareTo(str2);
if(result < 0) {
System.out.println("str1小于str2");
} else if(result > 0) {
System.out.println("str1大于str2");
} else {
System.out.println("str1等于str2");
}
输出结果为:
str1小于str2
5. 替换函数
字符串替换函数replace()将指定字符或字符串替换为另一个字符或字符串。例如:
String str = "hello world";
String newstr = str.replace('o', 'a');
System.out.println("替换后的字符串为:" + newstr);
输出结果为:
替换后的字符串为:hella warld
6. 格式化函数
字符串格式化函数format()可以将字符串格式化为指定的格式,例如:
String str = "hello";
double num = 3.1415926;
System.out.println(String.format("%s,%.2f", str, num));
输出结果为:
hello,3.14
7. 大小写转换函数
字符串大小写转换函数toLowerCase()将字符串中的所有字母转换为小写字母,toUpperCase()将字符串中所有字母转换为大写字母。例如:
String str = "Hello World";
String newstr1 = str.toLowerCase();
String newstr2 = str.toUpperCase();
System.out.println("小写字符串为:" + newstr1);
System.out.println("大写字符串为:" + newstr2);
输出结果为:
小写字符串为:hello world 大写字符串为:HELLO WORLD
综上所述,Java中字符串处理函数丰富而实用,开发者可以根据需要灵活使用。
