Java的String类:字符串处理函数的详解
Java的String类是一个非常常用的类,用于处理字符串。String类提供了很多字符串处理函数,下面对一些常用的函数进行详细介绍。
1. length()函数:返回字符串的长度,即字符的个数。例如:String str = "Hello World"; int len = str.length(); 这段代码中,len的值为11。
2. charAt()函数:返回指定索引位置的字符。索引从0开始。例如:String str = "Hello World"; char c = str.charAt(4); 这段代码中,c的值为'o'。
3. substring()函数:返回从指定索引位置开始到结束的子字符串。例如:String str = "Hello World"; String subStr = str.substring(6); 这段代码中,subStr的值为"World"。
4. indexOf()函数:返回指定字符 次出现的索引位置。例如:String str = "Hello World"; int index = str.indexOf('o'); 这段代码中,index的值为4。
5. lastIndexOf()函数:返回指定字符最后一次出现的索引位置。例如:String str = "Hello World"; int index = str.lastIndexOf('o'); 这段代码中,index的值为7。
6. startsWith()函数:判断字符串是否以指定的前缀开始。例如:String str = "Hello World"; boolean starts = str.startsWith("Hello"); 这段代码中,starts的值为true。
7. endsWith()函数:判断字符串是否以指定的后缀结束。例如:String str = "Hello World"; boolean ends = str.endsWith("World"); 这段代码中,ends的值为true。
8. toLowerCase()函数:将字符串转换为小写。例如:String str = "Hello World"; String lowerStr = str.toLowerCase(); 这段代码中,lowerStr的值为"hello world"。
9. toUpperCase()函数:将字符串转换为大写。例如:String str = "Hello World"; String upperStr = str.toUpperCase(); 这段代码中,upperStr的值为"HELLO WORLD"。
10. trim()函数:去除字符串两端的空白字符。例如:String str = " Hello World "; String trimStr = str.trim(); 这段代码中,trimStr的值为"Hello World"。
11. replace()函数:将字符串中的某个字符替换为另一个字符。例如:String str = "Hello World"; String replaceStr = str.replace('o', 'a'); 这段代码中,replaceStr的值为"Hella Warld"。
12. split()函数:以指定的分隔符将字符串拆分为多个字符串。例如:String str = "Hello,World"; String[] splitStr = str.split(","); 这段代码中,splitStr数组的值为["Hello", "World"]。
以上是String类的一些常用字符串处理函数。String类还提供了很多其他的功能,可以根据需求进行查阅和使用。
