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

内置Java函数:如何使用String类的函数

发布时间:2023-09-24 16:30:40

String类是Java中常用的类之一,它提供了许多用于操作字符串的函数。下面将介绍一些常用的String类函数以及它们的使用方法。

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

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

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

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

3. substring():返回指定索引范围内的子字符串。

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

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

String str = "hello world";
String upperStr = str.toUpperCase(); // upperStr的值为"HELLO WORLD"

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

String str = "HELLO WORLD";
String lowerStr = str.toLowerCase(); // lowerStr的值为"hello world"

6. indexOf():返回指定字符或字符串 次出现的索引位置。

String str = "Hello World";
int index = str.indexOf("o"); // index的值为4
int index2 = str.indexOf("o", 5); // index2的值为7

7. lastIndexOf():返回指定字符或字符串最后一次出现的索引位置。

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

8. replace():用指定的字符串替换原字符串中的特定字符或字符串。

String str = "Hello World";
String newStr = str.replace("o", "x"); // newStr的值为"Hellx Wxrld"

9. trim():去除字符串的前导空格和尾部空格。

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

10. split():根据指定的分隔符将字符串拆分成数组。

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

11. startsWith():判断字符串是否以指定的前缀开始。

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

12. endsWith():判断字符串是否以指定的后缀结束。

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

这些只是String类中的一部分常用函数,String类还提供了很多其他函数,可以根据具体的需求来选择使用。在使用String函数时,应注意处理可能出现的空指针异常和越界异常,以确保代码的稳定性和健壮性。