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

Java String函数库的常用函数及其用法

发布时间:2023-06-05 19:48:00

Java是一种很受欢迎的编程语言,String类是其中的一个核心类。在Java中,String类提供了很多常用的函数,这些函数可以用来操作文本和字符串。下面是Java String函数库的常用函数及其用法。

1. charAt(int index)

此函数返回表示指定索引处字符的Unicode代码点。索引参数必须大于或等于0且小于字符串的长度。

示例:

String str = "Hello World";
char c = str.charAt(0);
System.out.println(c);   //输出 H

2. toUpperCase()

此函数将字符串中的所有字符都转换为大写字母。

示例:

String str = "hello world";
String result = str.toUpperCase();
System.out.println(result);   //输出 HELLO WORLD

3. toLowerCase()

此函数将字符串中的所有字符都转换为小写字母。

示例:

String str = "HELLO WORLD";
String result = str.toLowerCase();
System.out.println(result);   //输出 hello world

4. indexOf(char ch)

此函数返回指定字符在字符串中 次出现的索引,如果没有找到该字符,则返回-1。

示例:

String str = "hello world";
int index = str.indexOf('o');
System.out.println(index);   //输出 4

5. lastIndexOf(char ch)

此函数返回指定字符在字符串中最后一次出现的索引,如果没有找到该字符,则返回-1。

示例:

String str = "hello world";
int index = str.lastIndexOf('o');
System.out.println(index);   //输出 7

6. substring(int beginIndex)

此函数返回一个新的字符串,它是从当前字符串的指定位置开始截取到字符串的末尾。

示例:

String str = "hello world";
String result = str.substring(6);
System.out.println(result);   //输出 world

7. substring(int beginIndex, int endIndex)

此函数返回一个新的字符串,它是从当前字符串的指定位置开始截取到指定位置的前一个字符。

示例:

String str = "hello world";
String result = str.substring(6, 8);
System.out.println(result);   //输出 wo

8. equals(String str)

此函数比较两个字符串是否相等,返回一个布尔值。

示例:

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

9. split(String regex)

此函数把当前字符串按照指定的正则表达式拆分成一个字符串数组。

示例:

String str = "hello,world";
String[] results = str.split(",");
for (String s : results) {
    System.out.println(s);
}

10. replace(char oldChar, char newChar)

此函数返回一个新的字符串,它将指定字符的所有出现替换为另一个指定的字符。

示例:

String str = "hello world";
String result = str.replace('o', '0');
System.out.println(result);   //输出 hell0 w0rld

以上就是Java String函数库的常用函数及其用法。这些函数可以帮助我们更加方便地操作字符串和文本。在实际开发中,我们还需要根据具体的需求来选择合适的函数。