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

Java中的字符串函数及使用

发布时间:2023-06-01 21:16:33

Java中的字符串是一种非常常用的数据类型,字符串函数则是用于对字符串进行操作和处理的函数。在Java中,字符串函数非常丰富,每个函数都有其独特的功能和使用方法。

1. length()函数

length()函数用于获取字符串的长度,其返回值为int类型。

例子:

String str = "hello world";

int length = str.length();

System.out.println("字符串长度为:" + length);

输出结果:

字符串长度为:11

2. charAt()函数

charAt()函数用于获取指定位置的字符,其参数为int类型,表示获取字符的位置,返回值为char类型。

例子:

String str = "hello world";

char ch = str.charAt(4);

System.out.println("第5个字符为:" + ch);

输出结果:

第5个字符为:o

3. concat()函数

concat()函数用于将两个字符串连接起来,其参数为一个字符串,返回值为一个新的字符串。

例子:

String str1 = "hello";

String str2 = "world";

String str3 = str1.concat(str2);

System.out.println("连接后的字符串为:" + str3);

输出结果:

连接后的字符串为:helloworld

4. equals()函数

equals()函数用于比较两个字符串是否相等,其参数为一个字符串,返回值为boolean类型。

例子:

String str1 = "hello";

String str2 = "hello";

boolean flag = str1.equals(str2);

if (flag) {

    System.out.println("两个字符串相等");

} else {

    System.out.println("两个字符串不相等");

}

输出结果:

两个字符串相等

5. indexOf()函数

indexOf()函数用于查找一个字符在字符串中的位置,其参数为一个字符,返回值为int类型。若字符串中不存在该字符,则返回-1。

例子:

String str = "hello world";

int index = str.indexOf('o');

System.out.println("字符o在字符串中的位置为:" + index);

输出结果:

字符o在字符串中的位置为:4

6. toLowerCase()函数

toLowerCase()函数用于将字符串中的大写字符转换成小写字符,返回值为一个新的字符串。

例子:

String str = "Hello World";

String lowerStr = str.toLowerCase();

System.out.println("转换后的字符串为:" + lowerStr);

输出结果:

转换后的字符串为:hello world

7. toUpperCase()函数

toUpperCase()函数用于将字符串中的小写字符转换成大写字符,返回值为一个新的字符串。

例子:

String str = "Hello World";

String upperStr = str.toUpperCase();

System.out.println("转换后的字符串为:" + upperStr);

输出结果:

转换后的字符串为:HELLO WORLD

8. trim()函数

trim()函数用于去除字符串中的空格,返回值为一个新的字符串。

例子:

String str = "   hello world    ";

String trimStr = str.trim();

System.out.println("去除空格后的字符串为:" + trimStr);

输出结果:

去除空格后的字符串为:hello world

9. substring()函数

substring()函数用于获取字符串的子串,其参数为int类型,表示子串的开始位置,返回值为一个新的字符串。

例子:

String str = "hello world";

String subStr = str.substring(6);

System.out.println("获取的子串为:" + subStr);

输出结果:

获取的子串为:world

以上为部分字符串函数及其使用。在实际开发中,字符串函数的使用范围非常广泛,可以帮助我们处理和操作各种文本相关的数据。