10个常见的Java字符串函数及其用途
1. length()函数:用于获取字符串的长度,即字符串中字符的数量。例如:String str = "Hello World"; int len = str.length(); // len的值为11。
2. charAt()函数:用于获取字符串中指定位置的字符。例如:String str = "Hello World"; char firstChar = str.charAt(0); // firstChar的值为'H'。
3. indexOf()函数:用于查找字符串中特定字符或子串的位置。如果找到,返回该字符或子串在字符串中 次出现的索引位置;如果未找到,返回-1。例如:String str = "Hello World"; int index = str.indexOf("Wor"); // index的值为6。
4. substring()函数:用于截取字符串中的一部分。可以传递一个起始索引和一个结束索引作为参数,返回值为截取后的子串。例如:String str = "Hello World"; String subStr = str.substring(0, 5); // subStr的值为"Hello"。
5. toUpperCase()函数:用于将字符串中的所有字母转换为大写形式。例如:String str = "Hello World"; String upperStr = str.toUpperCase(); // upperStr的值为"HELLO WORLD"。
6. toLowerCase()函数:用于将字符串中的所有字母转换为小写形式。例如:String str = "Hello World"; String lowerStr = str.toLowerCase(); // lowerStr的值为"hello world"。
7. trim()函数:用于去除字符串中的前导和后缀空白符(即空格、换行符等)。例如:String str = " Hello World "; String trimStr = str.trim(); // trimStr的值为"Hello World"。
8. replace()函数:用于替换字符串中的某个字符或子串。可以传递两个参数:要替换的字符或子串和替换后的字符串。例如:String str = "Hello World"; String replaceStr = str.replace("l", "L"); // replaceStr的值为"HeLLo WorLd"。
9. equals()函数:用于判断两个字符串是否相等。如果两个字符串的内容相同,则返回true;否则返回false。例如:String str1 = "Hello World"; String str2 = "hello world"; boolean isEqual = str1.equals(str2); // isEqual的值为false。
10. compareTo()函数:用于比较两个字符串的大小关系。如果两个字符串相等,则返回0;如果调用该函数的字符串小于传递的参数字符串,则返回负数;如果大于,则返回正数。例如: String str1 = "Apple"; String str2 = "Banana"; int result = str1.compareTo(str2); // result的值为-1,因为"Apple"的ASCII码值小于"Banana"的ASCII码值。
