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

Java中字符串函数的常见用法与示例

发布时间:2023-05-26 05:46:30

Java中字符串函数的常见用法是对字符串进行处理和转换。以下是一些常见的函数和示例:

1. length():返回字符串的长度。

示例:

String str = "Hello World";

int length = str.length(); // length = 11

2. charAt(index):返回索引处的字符。

示例:

String str = "Hello World";

char ch = str.charAt(1); // ch = 'e'

3. substring(startIndex):返回从指定索引开始到字符串结尾的子字符串。

示例:

String str = "Hello World";

String subStr = str.substring(6); // subStr = "World"

4. substring(startIndex, endIndex):返回从startIndex到endIndex-1的子字符串。

示例:

String str = "Hello World";

String subStr = str.substring(0, 5); // subStr = "Hello"

5. toUpperCase():将字符串转换为大写。

示例:

String str = "Hello World";

String upperStr = str.toUpperCase(); // upperStr = "HELLO WORLD"

6. toLowerCase():将字符串转换为小写。

示例:

String str = "Hello World";

String lowerStr = str.toLowerCase(); // lowerStr = "hello world"

7. trim():去掉字符串前后的空格。

示例:

String str = " Hello World ";

String trimStr = str.trim(); // trimStr = "Hello World"

8. indexOf(str):返回字符串中匹配到的 个子字符串的索引。

示例:

String str = "Hello World";

int index = str.indexOf("World"); // index = 6

9. lastIndexOf(str):返回字符串中匹配到的最后一个子字符串的索引。

示例:

String str = "Hello World";

int index = str.lastIndexOf("l"); // index = 9

10. replace(oldStr, newStr):将所有匹配到的oldStr替换为newStr。

示例:

String str = "Hello World";

String replaceStr = str.replace("World", "Java"); // replaceStr = "Hello Java"

11. startsWith(str):判断字符串是否以指定的字符串开头。

示例:

String str = "Hello World";

boolean isStart = str.startsWith("Hello"); // isStart = true

12. endsWith(str):判断字符串是否以指定的字符串结尾。

示例:

String str = "Hello World";

boolean isEnd = str.endsWith("World"); // isEnd = true

13. contains(str):判断字符串是否包含指定的子字符串。

示例:

String str = "Hello World";

boolean isContain = str.contains("L"); // isContain = true

14. split(str):将字符串按照指定的分隔符拆分成字符串数组。

示例:

String str = "Hello,World";

String[] splitStr = str.split(","); // splitStr = {"Hello", "World"}

15. substringBefore(str):返回字符串中指定字符串之前的子字符串。

示例:

String str = "Hello World";

String subStr = StringUtils.substringBefore(str, " "); // subStr = "Hello"

总之,Java中的字符串函数非常丰富和强大,开发者可以根据不同的需求使用不同的函数来操作字符串,使编写程序更加高效和便捷。