java中的String类的常用方法

1.Java charAt() 方法

 

charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。

public class Test {

    public static void main(String args[]) {
        String s = "sworddancing";
        char result = s.charAt(8);//其中index的范围是0-length-1
        System.out.println(result);
    }
}

 

 2.Java concat() 方法

public String concat(String s)
public class Test {
    public static void main(String args[]) {
        String s = "swprddancing:";
        s = s.concat("www.runoob.com");
        System.out.println(s);
    }
}

 

3.Java equals() 方法

public boolean equals(Object anObject)

 

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("runoob");
        String Str2 = Str1;
        String Str3 = new String("runoob");
        boolean retVal;

        retVal = Str1.equals( Str2 );
        System.out.println("返回值 = " + retVal );

        retVal = Str1.equals( Str3 );
        System.out.println("返回值 = " + retVal );
    }
}

 

4.Java compareTo() 方法

int compareTo(Object o) 或 int compareTo(String anotherString)


public class Test {
 
    public static void main(String args[]) {
        String str1 = "Strings";
        String str2 = "Strings";
        String str3 = "Strings123";
 
        int result = str1.compareTo( str2 );
        System.out.println(result);
      
        result = str2.compareTo( str3 );
        System.out.println(result);
     
        result = str3.compareTo( str1 );
        System.out.println(result);
    }
}

 

5.Java length() 方法

public int 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());
    }
}

 

6.Java toCharArray() 方法

public char[] toCharArray()
public class Test {
    public static void main(String args[]) {
        String Str = new String("www.runoob.com");

        System.out.print("返回值 :" );
        System.out.println( Str.toCharArray() );
    }
}

 另外有三个函数:

String trim()

String toLowerCase()

 String toUpperCase()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值