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

在Java中如何使用字符串函数?

发布时间:2023-10-29 19:40:44

在Java中,有很多字符串函数可用来处理和操作字符串。下面是一些常用的字符串函数及其使用方法。

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

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

2. toUpperCase()和toLowerCase():将字符串转换为大写或小写。

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

3. charAt(index):返回指定索引位置的字符。

String str = "Hello World";
char ch = str.charAt(4); // ch的值为'o'

4. substring(beginIndex)和substring(beginIndex, endIndex):返回指定开始索引和结束索引之间的子字符串。

String str = "Hello World";
String substr1 = str.substring(6); // substr1的值为"World"
String substr2 = str.substring(0, 5); // substr2的值为"Hello"

5. indexOf(str)和lastIndexOf(str):返回指定字符串出现的 个或最后一个索引位置。

String str = "Hello World";
int firstIndex = str.indexOf("o"); // firstIndex的值为4
int lastIndex = str.lastIndexOf("o"); // lastIndex的值为7

6. replace(oldStr, newStr):将指定的字符串替换为新的字符串。

String str = "Hello World";
String replaced = str.replace("World", "Universe"); // replaced的值为"Hello Universe"

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

String str = "Hello World";
boolean contains = str.contains("World"); // contains的值为true

8. split(delimiter):将字符串按指定分隔符分割为数组。

String str = "Hello,World";
String[] splitStr = str.split(","); // splitStr的值为["Hello", "World"]

9. trim():去除字符串前后的空格。

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

10. startsWith(str)和endsWith(str):判断字符串是否以指定的子字符串开始或结束。

String str = "Hello World";
boolean starts = str.startsWith("Hello"); // starts的值为true
boolean ends = str.endsWith("World"); // ends的值为true

上述是一些常见字符串函数的用法,你可以根据你的需求选择合适的函数来处理和操作字符串。