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

Java中常用的字符串操作函数总结

发布时间:2023-05-21 07:07:10

Java中的字符串是最常用的数据类型之一。在对字符串进行操作时,需要使用很多常用的字符串操作函数。本文将对这些函数进行总结。

1.字符串拼接

在Java中,字符串拼接可以使用加号“+”,也可以使用concat函数。比如:

String str1 = "Hello";

String str2 = "world";

String str3 = str1 + str2; // str3的值为"Helloworld"

String str4 = str1.concat(str2); // str4的值为"Helloworld"

2.字符串长度

可以使用length函数来获取字符串的长度。比如:

String str = "Hello world";

int len = str.length(); // len的值为11

3.字符串截取

使用substring函数可以截取字符串的一部分。比如:

String str = "Hello world";

String sub1 = str.substring(0, 5); // sub1的值为"Hello"

String sub2 = str.substring(6); // sub2的值为"world"

4.字符串替换

使用replace函数可以将字符串中的某个子串替换为另一个字符串。比如:

String str = "Hello world";

String newStr = str.replace("world", "Java"); // newStr的值为"Hello Java"

5.字符串转换

可以使用valueOf函数将其他类型的数据转换为字符串类型,也可以使用parse函数将字符串转换为其他类型的数据。比如:

int num = 10;

String str = String.valueOf(num); // str的值为"10"

int newNum = Integer.parseInt(str); // newNum的值为10

6.字符串去空格

使用trim函数可以去除字符串两端的空格。比如:

String str = " Hello world ";

String newStr = str.trim(); // newStr的值为"Hello world"

7.字符串查找

可以使用indexOf函数查找某个字符或子串在字符串中的位置。比如:

String str = "Hello world";

int index1 = str.indexOf('o'); // index1的值为4

int index2 = str.indexOf("world"); // index2的值为6

8.字符串大小写转换

使用toUpperCase函数可以将字符串转换为大写,使用toLowerCase函数可以将字符串转换为小写。比如:

String str = "Hello world";

String upper = str.toUpperCase(); // upper的值为"HELLO WORLD"

String lower = str.toLowerCase(); // lower的值为"hello world"

总结

以上就是Java中常用的字符串操作函数的总结。这些函数是Java中最基础也最常用的字符串操作函数,掌握了这些函数,就能够更好地处理字符串相关的操作。