使用Java的字符串函数处理字符串的常见操作
发布时间:2023-07-03 04:09:45
Java中提供了许多字符串函数来处理常见的字符串操作。下面是一些常见的字符串函数及其用法:
1. length(): 获取字符串的长度。
String str = "Hello World"; int length = str.length(); // length = 11
2. charAt(index): 获取指定索引位置的字符。
String str = "Hello World"; char ch = str.charAt(0); // ch = 'H'
3. substring(startIndex)和substring(startIndex, endIndex): 返回从指定索引位置开始到字符串末尾的子字符串,或从指定索引位置开始到指定索引位置前的子字符串。
String str = "Hello World"; String substr1 = str.substring(6); // substr1 = "World" String substr2 = str.substring(0, 5); // substr2 = "Hello"
4. toLowerCase()和toUpperCase(): 将字符串转换为小写或大写。
String str = "Hello World"; String lowerStr = str.toLowerCase(); // lowerStr = "hello world" String upperStr = str.toUpperCase(); // upperStr = "HELLO WORLD"
5. trim(): 去除字符串开头和结尾的空格。
String str = " Hello World "; String trimmedStr = str.trim(); // trimmedStr = "Hello World"
6. startsWith(prefix)和endsWith(suffix): 判断字符串是否以指定的前缀或后缀开始或结束。
String str = "Hello World";
boolean startsWithHello = str.startsWith("Hello"); // startsWithHello = true
boolean endsWithWorld = str.endsWith("World"); // endsWithWorld = true
7. indexOf(str)和lastIndexOf(str): 返回指定字符串在原字符串中 次或最后一次出现的位置,若未找到返回-1。
String str = "Hello World";
int firstIndex = str.indexOf("o"); // firstIndex = 4
int lastIndex = str.lastIndexOf("o"); // lastIndex = 7
8. replace(oldChar, newChar)和replaceAll(regex, replacement): 将指定字符或正则表达式匹配的部分替换为新字符或字符串。
String str = "Hello World";
String replacedStr = str.replace("o", "x"); // replacedStr = "Hellx Wxrld"
String regexReplacedStr = str.replaceAll("[aeiou]", "-"); // regexReplacedStr = "H-ll- W-rld"
9. split(delimiter): 使用指定的分割符将字符串拆分为字符串数组。
String str = "Hello,World";
String[] parts = str.split(","); // parts = ["Hello", "World"]
10. concat(str): 将指定字符串连接到原字符串的末尾。
String str = "Hello";
String newStr = str.concat(" World"); // newStr = "Hello World"
这些只是Java字符串类(String)的一些常见操作,可以根据具体需求进行使用和组合,以实现更复杂的字符串处理任务。
