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

Java中的字符串函数:学习Java中字符串处理的基本函数及其应用

发布时间:2023-06-19 18:32:52

Java中的字符串函数是Java编程语言中最常用的函数之一。在程序开发中,字符串处理是相当常见的操作。Java中提供了一系列的字符串函数来处理字符串,使得我们可以更加方便地对字符串进行操作。本文将介绍Java中的一些常用的字符串处理函数及其应用。

1. length()函数

length()函数返回字符串的长度。例如:

String str = "hello world";
int len = str.length();
System.out.println(len);

输出为:11

2. charAt()函数

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

String str = "hello world";
char c = str.charAt(0);
System.out.println(c);

输出为:h

3. substring()函数

substring()函数返回字符串从指定位置开始(包含该位置),到指定位置结束(不包含该位置)的子字符串。例如:

String str = "hello world";
String subStr = str.substring(3, 7);
System.out.println(subStr);

输出为:lo w

4. indexOf()函数

indexOf()函数返回字符串中指定子字符串的位置。例如:

String str = "hello world";
int index = str.indexOf("world");
System.out.println(index);

输出为:6

5. lastIndexOf()函数

lastIndexOf()函数返回字符串中指定子字符串最后出现的位置。例如:

String str = "hello world world";
int index = str.lastIndexOf("world");
System.out.println(index);

输出为:12

6. replace()函数

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

String str = "hello world";
String newStr = str.replace("world", "java");
System.out.println(newStr);

输出为:hello java

7. trim()函数

trim()函数删除字符串前后的空格。例如:

String str = "   hello world   ";
String newStr = str.trim();
System.out.println(newStr);

输出为:hello world

8. toLowerCase()函数

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

String str = "Hello World";
String newStr = str.toLowerCase();
System.out.println(newStr);

输出为:hello world

9. toUpperCase()函数

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

String str = "Hello World";
String newStr = str.toUpperCase();
System.out.println(newStr);

输出为:HELLO WORLD

10. equals()函数

equals()函数用于比较两个字符串是否相等。例如:

String str1 = "hello world";
String str2 = "hello world";
boolean result = str1.equals(str2);
System.out.println(result);

输出为:true

11. compareTo()函数

compareTo()函数比较两个字符串的大小。例如:

String str1 = "hello";
String str2 = "world";
int result = str1.compareTo(str2);
System.out.println(result);

输出为:-15,因为'h'在字母表中比'w'要小。

总结:

Java中的字符串函数非常丰富,掌握常用的字符串处理函数能够大幅提高编程效率。除了本文中介绍的函数,Java中还有很多其他的字符串函数,大家可以参考官方文档进一步了解。