Java中的字符串函数:实现基本操作和字符串处理
Java中的字符串函数主要用于实现对字符串的基本操作和字符串处理。下面将介绍一些常用的字符串函数及其功能。
1. length():返回字符串的长度。例如:String str = "Hello World"; int len = str.length(); // len的值为11。
2. charAt(int index):返回字符串中指定位置的字符。例如:String str = "Hello World"; char ch = str.charAt(0); // ch的值为'H'。
3. indexOf(String str):返回字符串中指定子串 次出现的位置。例如:String str = "Hello World"; int index = str.indexOf("o"); // index的值为4。
4. lastIndexOf(String str):返回字符串中指定子串最后一次出现的位置。例如:String str = "Hello World"; int index = str.lastIndexOf("o"); // index的值为7。
5. substring(int beginIndex, int endIndex):返回字符串中指定范围的子串。例如:String str = "Hello World"; String subStr = str.substring(6, 11); // subStr的值为"World"。
6. toUpperCase():将字符串转换为大写形式。例如:String str = "Hello World"; String upperStr = str.toUpperCase(); // upperStr的值为"HELLO WORLD"。
7. toLowerCase():将字符串转换为小写形式。例如:String str = "Hello World"; String lowerStr = str.toLowerCase(); // lowerStr的值为"hello world"。
8. trim():去除字符串首尾的空格。例如:String str = " Hello World "; String trimmedStr = str.trim(); // trimmedStr的值为"Hello World"。
9. replace(char oldChar, char newChar):将字符串中指定字符替换为新字符。例如:String str = "Hello World"; String replacedStr = str.replace('o', 'x'); // replacedStr的值为"Hellx Wxrld"。
10. split(String regex):将字符串分割为子串数组。例如:String str = "Hello,World"; String[] arr = str.split(","); // arr的值为{"Hello", "World"}。
11. startsWith(String prefix):判断字符串是否以指定前缀开头。例如:String str = "Hello World"; boolean starts = str.startsWith("Hello"); // starts的值为true。
12. endsWith(String suffix):判断字符串是否以指定后缀结尾。例如:String str = "Hello World"; boolean ends = str.endsWith("World"); // ends的值为true。
14. equals(String str):判断字符串是否与指定字符串相等。例如:String str1 = "Hello"; String str2 = "World"; boolean equal = str1.equals(str2); // equal的值为false。
以上是一些常用的字符串函数,通过使用这些函数,我们可以对字符串进行各种基本操作和字符串处理,使得我们能够更方便地对字符串进行操作和处理。
