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

与字符串相关的Java函数介绍

发布时间:2023-06-18 20:11:22

Java中有很多与字符串相关的函数,以下是一些常用的函数的介绍。

1. length()函数

该函数返回一个字符串的长度。

String str = "Hello World!";
int len = str.length(); // len的值为12

2. compareTo()函数

该函数比较两个字符串的字典顺序。当字符串相同时,返回0;当str1大于str2时,返回一个正数;当str1小于str2时,返回一个负数。

String str1 = "Hello";
String str2 = "World";
int result = str1.compareTo(str2); // result的值为-15
result = str2.compareTo(str1); // result的值为15
result = str1.compareTo("Hello"); // result的值为0

3. indexOf()函数

该函数返回一个子字符串在原字符串中第一次出现的位置。如果找不到该子字符串,则返回-1。

String str = "Hello World!";
int index = str.indexOf("o"); // index的值为4
index = str.indexOf("a"); // index的值为-1

4. substring()函数

该函数返回一个字符串的子串,根据传入的参数不同,会有不同的结果。

String str = "Hello World!";
String sub = str.substring(3); //sub的值为"lo World!"
sub = str.substring(3, 7); //sub的值为"lo W"

5. replace()函数

该函数替换一个字符串中的字符。

String str = "Hello World!";
String newStr = str.replace("o", "a"); // newStr的值为"Hella Warld!"

6. toUpperCase()函数和toLowerCase()函数

这两个函数分别将一个字符串转换成大写和小写。

String str = "Hello World!";
String upperStr = str.toUpperCase(); // upperStr的值为"HELLO WORLD!"
String lowerStr = str.toLowerCase(); // lowerStr的值为"hello world!"

7. trim()函数

该函数去掉一个字符串两端的空格。

String str = "     Hello World!     ";
String sub = str.trim(); // sub的值为"Hello World!"

8. startsWith()函数和endsWith()函数

这两个函数分别用来判断一个字符串是否以特定的子字符串开头或结尾。

String str = "Hello World!";
boolean b1 = str.startsWith("Hell"); // b1的值为true
boolean b2 = str.endsWith("!"); // b2的值为true

9. equals()函数和equalsIgnoreCase()函数

这两个函数用来比较两个字符串是否相等,区别在于equalsIgnoreCase()函数忽略大小写。

String str1 = "Hello";
String str2 = "hello";
boolean b1 = str1.equals(str2); // b1的值为false
boolean b2 = str1.equalsIgnoreCase(str2); // b2的值为true

10. split()函数

该函数按照指定的分隔符将一个字符串分割为多个子字符串,并将其存储在一个字符串数组中。

String str = "apple,banana,orange";
String[] arr = str.split(","); // arr的值为["apple","banana","orange"]