温馨提示×

java字符串函数有哪些

养鱼的猫咪
438
2021-04-19 12:13:32
栏目: 编程语言

java中常用的字符串函数有:1.equals()函数,比较字符串是否相等;2.split()函数,拆分字符串;3.replace()函数,替换字符串;4.indexof()函数,返回字符索引;5.substring()函数,返回子字符串;6.concat()函数,连接字符串;7.toLowerCase()函数,将字符串转换为小写;8.toUpperCase()函数,将字符串转换为大写;9.length()函数,返回字符串长度;

java字符串函数有哪些

java中常用的字符串函数有以下几种

1.equals()函数

java中equals()函数的作用是用于比较两个字符串的变量值是否相等。

s1 = new String("abc");s2 = new String("abc");s1.equals(s2) //返回 true

2.split()函数

java中split()函数的作用是用于根据给定的正则表达式对字符串进行拆分。

String str = "one two three, four";

String[] tokens = str.split(" ");

for (String s: tokens)

System.out.println(s);


3.replace()函数

java中replace()函数的作用是用于将字符串中某一个相同的信息替换为另外一个字符串。

String a = "hello wrold!";

String b = "China!";

a = a.replace("wrold!",b);

System.out.println(a); //返回hello China!


4.indexof()函数

java中indexof()函数的作用是用于返回一个字符在字符串中的索引,如字符串中没有该字符,则返回-1。

String str = "01234567890123456789";System.out.println(str.indexOf("123")); //返回 1System.out.println(str.indexOf("321")); //返回 -1

5.substring()函数

java中substring()函数的作用是用于返回字符串的子字符串。

public class RunoobTest {

    public static void main(String args[]) {

        String Str = new String("This is text");

        System.out.print("返回值 :" );//返回is text

        System.out.println(Str.substring(4) );

        System.out.print("返回值 :" );//返回is te

        System.out.println(Str.substring(4, 10) );

    }

}

6.concat()函数

java中concat()函数的作用是用于将指定的字符串参数连接到字符串上。

public class Test {

    public static void main(String args[]) {

        String s = "你好";

        s = s.concat("世界");

        System.out.println(s);

    }

}

输出结果为:

你好世界

7.toLowerCase()函数

java中toLowerCase()函数的作用是将字符串大写字符转换为小写。

public class Test {

    public static void main(String args[]) {

        System.out.println(Character.toLowerCase('HELLO WORLD!'));

    }

}

输出结果为:

hello world!

8.toUpperCase()函数

java中toUpperCase()函数的作用是将字符串小写字符转换为大写。

public class Test {

    public static void main(String args[]) {

        System.out.println(Character.toUpperCase('hello world!'));

    }

}

输出结果为:

HELLO WORLD!

9.length()函数

java中length()函数的作用是用于返回字符串的长度。

public static void main(String args[]) {

        String site = "hello world!";

        int len = site.length();

        System.out.println( len );    //返回12

   }

}


0