欢迎访问宙启技术站
智能推送

Java中常用字符串函数的详细解读和应用

发布时间:2023-06-04 05:24:45

Java语言中有许多字符串函数,可以帮助我们更方便地处理字符串。在本文中,我们将详细解读并应用Java中常用的字符串函数。

1. length()函数

语法:string.length()

功能:返回字符串的长度。

示例代码:

String str = "hello world";
int len = str.length();
System.out.println(len); // 输出 11

2. charAt()函数

语法:string.charAt(index)

功能:返回指定位置的字符。

示例代码:

String str = "hello world";
char ch = str.charAt(1);
System.out.println(ch); // 输出 e

3. indexOf()函数

语法:string.indexOf(str)

功能:返回字符串中 个出现的指定字符串的索引,如果没有找到,返回-1。

示例代码:

String str = "hello world";
int index = str.indexOf("world");
System.out.println(index); // 输出 6

4. substring()函数

语法:string.substring(beginIndex, endIndex)

功能:返回从指定位置开始到结束位置之间的子字符串。

示例代码:

String str = "hello world";
String substr = str.substring(6, 11);
System.out.println(substr); // 输出 world

5. trim()函数

语法:string.trim()

功能:去除字符串前后的空格。

示例代码:

String str = "    hello world    ";
String trimStr = str.trim();
System.out.println(trimStr); // 输出 hello world

6. replace()函数

语法:string.replace(oldChar, newChar)

功能:替换字符串中的指定字符。

示例代码:

String str = "hello world";
String newStr = str.replace("l", "L");
System.out.println(newStr); // 输出 heLLo worLd

7. concat()函数

语法:string.concat(str)

功能:连接两个字符串。

示例代码:

String str1 = "hello";
String str2 = "world";
String str3 = str1.concat(str2);
System.out.println(str3); // 输出 helloworld

8. startsWith()函数

语法:string.startsWith(str)

功能:检查字符串是否以指定字符串开头。

示例代码:

String str = "hello world";
boolean isStartWithHello = str.startsWith("hello");
System.out.println(isStartWithHello); // 输出 true

9. endsWith()函数

语法:string.endsWith(str)

功能:检查字符串是否以指定字符串结尾。

示例代码:

String str = "hello world";
boolean isEndWithWorld = str.endsWith("world");
System.out.println(isEndWithWorld); // 输出 true

10. toUpperCase()函数

语法:string.toUpperCase()

功能:将字符串中的所有字符转换为大写字母。

示例代码:

String str = "hello world";
String upperStr = str.toUpperCase();
System.out.println(upperStr); // 输出 HELLO WORLD

11. toLowerCase()函数

语法:string.toLowerCase()

功能:将字符串中的所有字符转换为小写字母。

示例代码:

String str = "HELLO WORLD";
String lowerStr = str.toLowerCase();
System.out.println(lowerStr); // 输出 hello world

12. split()函数

语法:string.split(str)

功能:将字符串按照指定字符串分割成字符串数组。

示例代码:

String str = "hello,world";
String[] splitStr = str.split(",");
for (String s : splitStr) {
    System.out.println(s);
} // 输出 hello 和 world

以上是Java中常用的字符串函数,掌握它们可以帮助我们更方便地处理字符串,提高编程效率。