Java之常用字符串处理函数
Java中有大量的字符串处理函数,这些函数可以在日常编程中帮助开发人员更方便地实现字符串的操作。这篇文章将介绍Java中一些常用的字符串处理函数。
1. length()
在Java中,length()函数用于返回一个字符串的长度。例如:
String str = "hello";
int len = str.length();
// len will be 5
2. charAt()
charAt()函数用于返回一个字符串中指定位置的字符。例如:
String str = "hello";
char ch = str.charAt(1);
// ch will be 'e'
3. substring()
substring()函数用于返回一个字符串的子串。可以使用两个参数来指定子串的起始位置和终止位置。例如:
String str = "hello";
String sub = str.substring(1, 4);
// sub will be "ell"
4. equals()
equals()函数用于判断两个字符串是否相等。例如:
String str1 = "hello";
String str2 = "world";
boolean result1 = str1.equals(str2); // false
str1 = "hello";
str2 = "hello";
boolean result2 = str1.equals(str2); // true
5. compareTo()
compareTo()函数用于比较两个字符串的大小关系。它返回一个整数值,表示两个字符串的大小关系。例如:
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
// result will be a negative number because "apple" is smaller than "banana"
6. trim()
trim()函数用于去除一个字符串首尾的空格。例如:
String str = " hello ";
String trimmed = str.trim();
// trimmed will be "hello"
7. toLowerCase()和toUpperCase()
toLowerCase()函数用于将一个字符串中所有的大写字母转换为小写字母,toUpperCase()函数则相反,将所有小写字母转换为大写字母。例如:
String str = "HeLLo";
String lower = str.toLowerCase();
String upper = str.toUpperCase();
// lower will be "hello", upper will be "HELLO"
8. indexOf()和lastIndexOf()
indexOf()函数用于返回一个字符串中 次出现指定字符的位置,lastIndexOf()函数则相反,返回最后一次出现指定字符的位置。例如:
String str = "hello";
int first = str.indexOf("l");
int last = str.lastIndexOf("l");
// first will be 2, last will be 3
9. startsWith()和endsWith()
startsWith()函数用于判断一个字符串是否以指定字符串开头,endsWith()函数则相反,判断指定字符串是否是原字符串的结尾。例如:
String str = "hello";
boolean startsWithH = str.startsWith("h");
boolean endsWithO = str.endsWith("o");
// startsWithH will be true, endsWithO will be true
10. replace()和replaceAll()
replace()函数用于将一个字符串中指定的字符替换成另一个字符,replaceAll()函数则是将字符串中所有指定的字符都替换成目标字符。例如:
String str = "hello";
String replaced = str.replace("l", "L");
String replacedAll = str.replaceAll("l", "L");
// replaced will be "heLLo", replacedAll will be "heLLo"
这些函数只是Java中众多字符串处理函数的一部分。在日常编程中,开发人员可以根据需求选择不同的函数,以实现字符串的各种操作。
