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

处理字符串的常用Java函数有哪些?

发布时间:2023-06-15 12:51:48

Java是一种广泛使用的编程语言,用于开发各种应用程序。字符串是Java中最常见的数据类型之一,因此Java提供了许多用于处理字符串的常用函数。本文将介绍Java中常用的字符串函数。

1、length()函数

length()函数使用非常广泛,它返回一个字符串的长度。例如:

String str = "Hello world!";

int len = str.length();

System.out.println(len); //输出13

2、concat()函数

concat()函数将一个字符串连接到当前字符串的结尾。例如:

String str1 = "Hello";

String str2 = "world!";

String str3 = str1.concat(str2);

System.out.println(str3); //输出Hello world!

3、toLowerCase()和toUpperCase()函数

toLowerCase()函数将字符串中的所有字母转换为小写字母,而toUpperCase()函数将字符串中的所有字母转换为大写字母。例如:

String str = "Hello world!";

System.out.println(str.toLowerCase()); //输出hello world!

System.out.println(str.toUpperCase()); //输出HELLO WORLD!

4、charAt()函数

charAt()函数返回指定位置的字符。例如:

String str = "Hello world!";

System.out.println(str.charAt(4)); //输出o

5、substring()函数

substring()函数返回起始索引和结束索引之间的子字符串。例如:

String str = "Hello world!";

System.out.println(str.substring(6, 11)); //输出world

6、trim()函数

trim()函数删除字符串开头和结尾的空格。例如:

String str = "  Hello world!  ";

System.out.println(str.trim()); //输出Hello world!

7、startsWith()和endsWith()函数

startsWith()函数检查字符串是否以指定的前缀开头,而endsWith()函数检查字符串是否以指定的后缀结尾。例如:

String str = "Hello world!";

System.out.println(str.startsWith("Hello")); //输出true

System.out.println(str.endsWith("world!")); //输出true

8、replace()和replaceAll()函数

replace()函数将一个字符或字符串替换为另一个字符或字符串。例如:

String str = "Hello world!";

System.out.println(str.replace("Hello", "Hi")); //输出Hi world!

replaceAll()函数将一个正则表达式替换为另一个字符串。例如:

String str = "Hello world!";

System.out.println(str.replaceAll("o", "a")); //输出Hella warld!

9、split()函数

split()函数使用指定的字符串分隔符将字符串拆分为子字符串数组。例如:

String str = "apple,banana,orange";

String[] arr = str.split(",");

for (String s : arr) {

    System.out.println(s);

}

//输出apple

//    banana

//    orange

10、compareTo()函数

compareTo()函数比较两个字符串的字典顺序。例如:

String str1 = "apple";

String str2 = "orange";

int result = str1.compareTo(str2);

if (result < 0) {

    System.out.println(str1 + "在" + str2 + "之前");

} else if (result == 0) {

    System.out.println(str1 + "和" + str2 + "相等");

} else {

    System.out.println(str1 + "在" + str2 + "之后");

}

//输出apple在orange之前

11、valueOf()函数

valueOf()函数将一个非字符串对象转换为字符串。例如:

int num = 123;

String str = String.valueOf(num);

System.out.println(str); //输出123

12、format()函数

format()函数将指定的格式字符串和参数进行格式化。例如:

String name = "Tom";

int age = 18;

double score = 89.5;

String info = String.format("姓名:%s,年龄:%d,成绩:%.2f", name, age, score);

System.out.println(info); //输出姓名:Tom,年龄:18,成绩:89.50

总之,Java提供了许多常用的字符串函数,这些函数可以使开发人员更容易地处理字符串。掌握这些函数对于学习和使用Java编程语言非常重要。