Java中如何使用字符串相关的函数
发布时间:2023-07-02 11:20:13
Java中有很多字符串相关的函数,可以对字符串进行操作和处理。下面将介绍一些常用的字符串函数和它们的用法。
1. 字符串的长度:可以使用length()函数来获取字符串的长度。例如:
String str = "Hello World"; int len = str.length(); System.out.println(len); // 输出12
2. 字符串的连接:可以使用+运算符或concat()函数来连接两个字符串。例如:
String str1 = "Hello";
String str2 = "World";
String result1 = str1 + " " + str2;
System.out.println(result1); // 输出Hello World
String result2 = str1.concat(" ").concat(str2);
System.out.println(result2); // 输出Hello World
3. 字符串的截取:可以使用substring()函数来截取字符串的一部分。例如:
String str = "Hello World"; String result = str.substring(6); System.out.println(result); // 输出World result = str.substring(0, 5); System.out.println(result); // 输出Hello
4. 字符串的查找:可以使用indexOf()函数来查找某个字符或字符串在字符串中的位置。例如:
String str = "Hello World";
int index1 = str.indexOf('o');
System.out.println(index1); // 输出4
int index2 = str.indexOf("World");
System.out.println(index2); // 输出6
5. 字符串的替换:可以使用replace()函数来替换字符串中的某个字符或字符串。例如:
String str = "Hello World";
String result = str.replace('o', '0');
System.out.println(result); // 输出Hell0 W0rld
result = str.replace("World", "Java");
System.out.println(result); // 输出Hello Java
6. 字符串的分割:可以使用split()函数来将字符串按照指定的分隔符分割成字符串数组。例如:
String str = "Hello World";
String[] array = str.split(" ");
for (String s : array) {
System.out.println(s);
}
输出:
Hello World
7. 字符串的大小写转换:可以使用toLowerCase()和toUpperCase()函数来将字符串转换为全小写或全大写。例如:
String str = "Hello World"; String lowerCase = str.toLowerCase(); System.out.println(lowerCase); // 输出hello world String upperCase = str.toUpperCase(); System.out.println(upperCase); // 输出HELLO WORLD
8. 字符串的判断:可以使用startsWith()和endsWith()函数来判断字符串是否以指定的字符或字符串开头或结尾。例如:
String str = "Hello World";
boolean startsWithHello = str.startsWith("Hello");
System.out.println(startsWithHello); // 输出true
boolean endsWithWorld = str.endsWith("World");
System.out.println(endsWithWorld); // 输出true
9. 字符串的去除空格:可以使用trim()函数来去除字符串开头和结尾的空格。例如:
String str = " Hello World "; String trimmedStr = str.trim(); System.out.println(trimmedStr); // 输出Hello World
这些只是一些常用的字符串相关函数,Java中还有很多其他的字符串函数可以用来处理和操作字符串。要根据实际需求选择合适的函数来使用。
