Java中常用的字符串函数及示例
发布时间:2023-06-15 19:13:06
Java中的String类提供了很多常用的字符串函数,这些函数可以方便地对字符串进行处理和操作。本文将介绍一些常用的Java字符串函数及其示例。
1. length()
length()函数用来获取字符串的长度,即字符串中字符的个数。
示例:
String str = "Hello World!";
int len = str.length();
System.out.println("字符串长度为:" + len);
输出结果为:
字符串长度为:12
2. charAt()
charAt()函数用于获取指定位置的字符。
示例:
String str = "Hello World!";
char ch = str.charAt(1);
System.out.println("第二个字符为:" + ch);
输出结果为:
第二个字符为:e
3. substring()
substring()函数用于获取字符串的子串,即从指定位置开始的一段子字符串。
示例:
String str = "Hello World!";
String subStr = str.substring(6);
System.out.println("子字符串为:" + subStr);
输出结果为:
子字符串为:World!
4. indexOf()
indexOf()函数用于查找指定字符或子字符串在字符串中 次出现的位置。
示例:
String str = "Hello World!";
int index = str.indexOf("o");
System.out.println("'o'在字符串中的位置为:" + index);
输出结果为:
'o'在字符串中的位置为:4
5. lastIndexOf()
lastIndexOf()函数用于查找指定字符或子字符串在字符串中最后一次出现的位置。
示例:
String str = "Hello World!";
int index = str.lastIndexOf("l");
System.out.println("'l'最后一次出现的位置为:" + index);
输出结果为:
'l'最后一次出现的位置为:9
6. equals()
equals()函数用于比较两个字符串是否相等。
示例:
String str1 = "Hello";
String str2 = "hello";
if(str1.equals(str2)){
System.out.println("两个字符串相等。");
} else {
System.out.println("两个字符串不相等。");
}
输出结果为:
两个字符串不相等。
7. toUpperCase()
toUpperCase()函数用于将字符串中的所有字符转换为大写字母。
示例:
String str = "Hello World!";
String upperCaseStr = str.toUpperCase();
System.out.println("转换后的字符串为:" + upperCaseStr);
输出结果为:
转换后的字符串为:HELLO WORLD!
8. toLowerCase()
toLowerCase()函数用于将字符串中的所有字符转换为小写字母。
示例:
String str = "Hello World!";
String lowerCaseStr = str.toLowerCase();
System.out.println("转换后的字符串为:" + lowerCaseStr);
输出结果为:
转换后的字符串为:hello world!
9. trim()
trim()函数用于去除字符串两端的空格。
示例:
String str = " Hello World! ";
String trimStr = str.trim();
System.out.println("去除空格后的字符串为:" + trimStr);
输出结果为:
去除空格后的字符串为:Hello World!
10. replace()
replace()函数用于替换字符串中的指定字符或子字符串。
示例:
String str = "Hello World!";
String replaceStr = str.replace("o", "a");
System.out.println("替换后的字符串为:" + replaceStr);
输出结果为:
替换后的字符串为:Hella Warld!
以上是常用的Java字符串函数及其示例,这些函数可以在实际开发中帮助我们处理字符串。除了这些函数,String类还提供了许多其他的函数,可以根据实际需要进行选择和使用。
