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

详解Java中常用的字符串函数。

发布时间:2023-06-14 01:32:06

Java中字符串是非常常见的数据类型,所以Java中有丰富的库函数来操作字符串。本文将详细介绍Java中常用的字符串函数。

1. 字符串长度函数 - length()

length()函数用于获取字符串的长度。例如:

String str = "hello";

int len = str.length(); // 获取字符串长度,此时len的值为5

2. 字符串比较函数 - equals()和equalsIgnoreCase()

equals()函数用于比较两个字符串是否相等。如果两个字符串相等,则返回true,否则为false。例如:

String str1 = "hello";

String str2 = "world";

boolean equalsResult = str1.equals(str2); // 此时equalsResult的值为false

equalsIgnoreCase()函数同样用于比较字符串是否相等,但它不考虑大小写。例如:

String str1 = "HELLO";

String str2 = "hello";

boolean equalsIgnoreCaseResult = str1.equalsIgnoreCase(str2); // 此时equalsIgnoreCaseResult的值为true

3. 字符串截取 - substring()

substring()函数用于截取字符串的一部分,并返回一个新的字符串。例如:

String str = "hello world";

String substr = str.substring(0, 5); // 截取从0开始(包括0)到5(不包括5)的字符串,此时substr的值为"hello"

4. 字符串连接 - concat()和+

concat()函数用于将一个字符串连接到另一个字符串的末尾,并返回一个新的字符串。例如:

String str1 = "hello";

String str2 = "world";

String concatResult = str1.concat(str2); // 此时concatResult的值为"helloworld"

"+"操作符同样用于连接字符串。例如:

String str1 = "hello";

String str2 = "world";

String concatResult = str1 + str2; // 此时concatResult的值为"helloworld"

5. 字符串搜索 - indexOf()

indexOf()函数用于搜索一个字符串中是否包含另一个字符串,并返回匹配的位置。例如:

String str = "hello world";

int index = str.indexOf("world"); // 在str中搜索"world",返回其在字符串str中的位置(从0开始),此时index的值为6

6. 字符串分割 - split()

split()函数用于将一个字符串按照指定的分隔符分割成多个子字符串,并返回一个字符串数组。例如:

String str = "hello world";

String[] splitResult = str.split(" "); // 按照空格分割字符串,此时splitResult的值为{"hello", "world"}

7. 字符串替换 - replace()

replace()函数用于将一个字符串中的指定字符替换成另一个字符,并返回一个新的字符串。例如:

String str = "hello world";

String replaceResult = str.replace("world", "Java"); // 将字符串中的"world"替换成"Java",此时replaceResult的值为"hello Java"

8. 字符串转换 - toLowerCase()和toUpperCase()

toLowerCase()函数用于将一个字符串中的所有字符转换为小写,并返回一个新的字符串。例如:

String str = "HELLO";

String toLowerCaseResult = str.toLowerCase(); // 将字符串中的所有字符转换为小写,此时toLowerCaseResult的值为"hello"

toUpperCase()函数用于将一个字符串中的所有字符转换为大写,并返回一个新的字符串。例如:

String str = "hello";

String toUpperCaseResult = str.toUpperCase(); // 将字符串中的所有字符转换为大写,此时toUpperCaseResult的值为"HELLO"

9. 字符串空格处理 - trim()

trim()函数用于去除一个字符串首尾的空格,并返回一个新的字符串。例如:

String str = "   hello world   ";

String trimResult = str.trim(); // 去除字符串str的首尾空格,此时trimResult的值为"hello world"

总结

以上就是Java中常用的字符串函数,包括字符串长度函数、字符串比较函数、字符串截取、字符串连接、字符串搜索、字符串分割、字符串替换、字符串转换和字符串空格处理。掌握这些函数可以让我们更加方便地操作字符串,提高我们的编程效率。