Java中常见的字符串函数,一次学会多种用法
发布时间:2023-07-03 19:59:33
Java中常见的字符串函数有很多,以下是一些常用的字符串函数及其用法:
1. length():获取字符串的长度。例如:
String str = "Hello World"; int len = str.length(); System.out.println(len); // 输出结果:11
2. charAt(index):获取指定索引位置的字符。索引位置从0开始。例如:
String str = "Hello World"; char c = str.charAt(1); System.out.println(c); // 输出结果:e
3. substring(startIndex, endIndex):获取字符串的子串。startIndex为起始索引(包含),endIndex为结束索引(不包含)。例如:
String str = "Hello World"; String subStr = str.substring(6, 11); System.out.println(subStr); // 输出结果:World
4. indexOf(str):返回指定字符串在原字符串中第一次出现的索引位置。如果未找到,则返回-1。例如:
String str = "Hello World";
int index = str.indexOf("o");
System.out.println(index); // 输出结果:4
5. lastIndexOf(str):返回指定字符串在原字符串中最后一次出现的索引位置。如果未找到,则返回-1。例如:
String str = "Hello World";
int index = str.lastIndexOf("o");
System.out.println(index); // 输出结果:7
6. equals(str):比较两个字符串是否相等。例如:
String str1 = "Hello"; String str2 = "Hello"; boolean isEqual = str1.equals(str2); System.out.println(isEqual); // 输出结果:true
7. toUpperCase():将字符串转换为大写。例如:
String str = "hello"; String upperStr = str.toUpperCase(); System.out.println(upperStr); // 输出结果:HELLO
8. toLowerCase():将字符串转换为小写。例如:
String str = "HELLO"; String lowerStr = str.toLowerCase(); System.out.println(lowerStr); // 输出结果:hello
9. trim():去除字符串两端的空格。例如:
String str = " Hello World "; String trimmedStr = str.trim(); System.out.println(trimmedStr); // 输出结果:Hello World
10. replace(oldStr, newStr):用新字符串替换原字符串中的指定字符串。例如:
String str = "Hello World";
String newStr = str.replace("World", "Java");
System.out.println(newStr); // 输出结果:Hello Java
11. concat(str):拼接字符串。例如:
String str1 = "Hello"; String str2 = " World"; String concatStr = str1.concat(str2); System.out.println(concatStr); // 输出结果:Hello World
12. split(str):根据指定字符串分割字符串为数组。例如:
String str = "Hello,World,Java";
String[] arr = str.split(",");
System.out.println(arr[0]); // 输出结果:Hello
System.out.println(arr[1]); // 输出结果:World
System.out.println(arr[2]); // 输出结果:Java
13. startsWith(str):判断字符串是否以指定字符串开头。例如:
String str = "Hello World";
boolean isStartsWithHello = str.startsWith("Hello");
System.out.println(isStartsWithHello); // 输出结果:true
14. endsWith(str):判断字符串是否以指定字符串结尾。例如:
String str = "Hello World";
boolean isEndsWithWorld = str.endsWith("World");
System.out.println(isEndsWithWorld); // 输出结果:true
15. isEmpty():判断字符串是否为空。例如:
String str = ""; boolean isEmpty = str.isEmpty(); System.out.println(isEmpty); // 输出结果:true
以上是部分常用的字符串函数和用法,希望对你有帮助。
