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

Java函数使用:常见的Java字符串函数有哪些?

发布时间:2023-06-17 20:16:53

Java字符串函数是用来处理字符串数据的Java函数,这些函数广泛用于Java编程中。Java提供了很多有用的字符串函数,这些函数可以使开发人员更轻松地操作和处理字符串。在这篇文章中,我们将讨论一些常用的Java字符串函数。

1. length()

length()函数用于获取字符串的长度。该函数返回一个整数,表示字符串的字符数。比如:

String str = "Hello World";

int len = str.length();

System.out.println(len);

输出结果为:

11

2. equals()

equals()函数用于比较两个字符串是否相等。该函数返回一个布尔值,表示字符串是否相等。比如:

String str1 = "Hello World";

String str2 = "hello world";

boolean eq = str1.equals(str2);

System.out.println(eq);

输出结果为:

false

注意,equals()函数是区分大小写的。

3. equalsIgnoreCase()

equalsIgnoreCase()函数与equals()函数类似,但是它不区分大小写。比如:

String str1 = "Hello World";

String str2 = "hello world";

boolean eq = str1.equalsIgnoreCase(str2);

System.out.println(eq);

输出结果为:

true

4. toUpperCase()

toUpperCase()函数用于将字符串转换为大写。比如:

String str = "Hello World";

String upper = str.toUpperCase();

System.out.println(upper);

输出结果为:

HELLO WORLD

5. toLowerCase()

toLowerCase()函数用于将字符串转换为小写。比如:

String str = "Hello World";

String lower = str.toLowerCase();

System.out.println(lower);

输出结果为:

hello world

6. trim()

trim()函数用于去除字符串的首尾空格。比如:

String str = "   Hello World   ";

String trimmed = str.trim();

System.out.println(trimmed);

输出结果为:

Hello World

7. indexOf()

indexOf()函数用于查找字符串中第一次出现指定字符或子串的位置。该函数返回一个整数,表示指定字符或子串的位置。如果没有找到指定字符或子串,该函数返回-1。比如:

String str = "Hello World";

int index = str.indexOf("W");

System.out.println(index);

输出结果为:

6

8. lastIndexOf()

lastIndexOf()函数与indexOf()函数类似,只不过它是从字符串的末尾开始查找。比如:

String str = "Hello World";

int index = str.lastIndexOf("l");

System.out.println(index);

输出结果为:

9

9. replace()

replace()函数用于将字符串中指定字符或子串替换为新字符或新子串。比如:

String str = "Hello World";

String replaced = str.replace("o", "x");

System.out.println(replaced);

输出结果为:

Hellx Wxrld

10. substring()

substring()函数用于获取字符串的子串。该函数需要传入两个参数,分别表示子串的起始位置和结束位置。比如:

String str = "Hello World";

String sub = str.substring(6, 11);

System.out.println(sub);

输出结果为:

World

除了上述常用的Java字符串函数,还有很多其他有用的函数,如split()、concat()、startsWith()、endsWith()等等。了解这些函数能够帮助我们更方便地操作和处理字符串数据。