String中的常用方法

 

1,split()

split() 方法用于把一个字符串分割成字符串数组。

public class Test {
    public static void main(String args[]) {
    String str="How are you doing today ?"
    document.write(str.split(“ ”)+ "<br />");
    document.write(str.split("")+ "<br />");
    document.write(str.split("",3));
    } }

2,length()

      length()方法用于获取字符串的长度

 

public class Test {
    public static void main(String args[]) {
    string str1 = new String( "www.runoob.com" ) ;
    String str2 = new string( "runoob" );     system.out.print("字符串str1 长度:");
    system.out.println(Str1.length( ));     System.out.print("字符串str2长度: ");
    system.out.println(Str2.length());
    } }

3,取subString()

      substring()方法用于提取字符串中介于两个指定下标之间的字符。

public class Test {
    public static void main(String args[]) {
       String str="Hello world! ";
    document.write(str. substring( 3,7));
    } }

4,截取前后空白 trim()

trim()方法用于删除字符串的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等。

public class Test {
    public static void main(String args[]) {
        String Str = new String("    www.runoob.com    ");
        System.out.print("原始值 :" );
        System.out.println( Str );
        System.out.print("删除头尾空白 :" );
        System.out.println( Str.trim() );
    }
}

5,替换:replace()

replace()方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

public class Test {
    public static void main(String args[]) {
    var str="Welcome to Microsoft! ";
    str=str + "We are proud to announce that Microsoft has ";
    str=str + "one of the largest Web Developers sites in the world.";
    document.write(str.replace(/Microsoft/g, "W3School"));
 } }

 

posted @ 2021-03-31 16:47  大碟啊  阅读(109)  评论(0)    收藏  举报