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

Java中的常用函数:字符串相关函数

发布时间:2023-06-18 22:53:34

Java中的字符串相关函数广泛应用于字符串的处理,字符串的使用是编程语言中的常见操作。在Java中字符串的操作很方便,大多数字符串操作可以使用预定义的字符串方法进行操作。下面是Java中常用的字符串相关函数:

1. 字符串长度函数length():该函数用于返回一个字符串的长度,即字符串中的字符数目。例如:

String str = "hello world!";
int len = str.length();
System.out.println(len); // 输出 12

2. 字符串查找函数indexOf():该函数用于在一个字符串中查找某个子串,并返回与该子串匹配的第一个字符的位置。例如:

String str = "hello world!";
int index = str.indexOf("world");
System.out.println(index); // 输出 6

3. 字符串截取函数substring():该函数用于从一个字符串中提取指定的子串,它需要两个参数,分别是提取起始位置和截取的长度。例如:

String str = "hello world!";
String sub = str.substring(6, 11);
System.out.println(sub); // 输出 world

4. 字符串分割函数split():该函数用于将一个字符串按照指定的分隔符进行分割,并返回一个字符串数组。例如:

String str = "hello,world";
String[] arr = str.split(",");
System.out.println(Arrays.toString(arr)); // 输出 [hello, world]

5. 字符串替换函数replace():该函数用于将一个字符串中的指定子串替换为另一个指定的字符串。例如:

String str = "hello world!";
String newStr = str.replace("world", "JAVA");
System.out.println(newStr); // 输出 hello JAVA!

6. 字符串大写函数toUpperCase():该函数用于将一个字符串中的所有字母都转换为大写字母。例如:

String str = "hello world!";
String newStr = str.toUpperCase();
System.out.println(newStr); // 输出 HELLO WORLD!

7. 字符串小写函数toLowerCase():该函数用于将一个字符串中的所有字母都转换为小写字母。例如:

String str = "HELLO WORLD!";
String newStr = str.toLowerCase();
System.out.println(newStr); // 输出 hello world!

8. 字符串去除空格函数trim():该函数用于去除一个字符串的首尾空格。例如:

String str = " hello world! ";
String newStr = str.trim();
System.out.println(newStr); // 输出hello world!

9. 字符串比较函数equals():该函数用于比较两个字符串的内容是否相同。例如:

String str1 = "hello";
String str2 = "hello";
boolean equals = str1.equals(str2);
System.out.println(equals); // 输出 true

10. 字符串忽略大小写的比较函数equalsIgnoreCase():该函数用于比较两个字符串的内容是否相同,不区分大小写。例如:

String str1 = "Hello";
String str2 = "hello";
boolean equals = str1.equalsIgnoreCase(str2);
System.out.println(equals); // 输出 true

以上就是Java中常用的字符串相关函数。这些函数可以帮助我们轻松快捷地处理字符串,提高程序开发效率。在编写程序时,要灵活运用这些函数,提高自己的编程技能。