String的用法——其餘功能

package cn.itcast_06;
/*code

  • String類的其餘功能:
  • 替換功能:
  • String replace(char old,char new)
  • String replace(String old,String new)
  • 去除字符串兩空格:
  • String trim()
  • 按字典順序比較兩個字符串(大小)
  • int compareTo(String str)//區分大小寫
  • int compareToIgnoreCase(String str)//不區分大小寫
  • */

public class StringDemo {字符串

public static void main(String[] args) {
    // TODO Auto-generated method stub
    //替換功能
    String s1 = "helloworld";
    String s2 = s1.replace('l', 'k');
    String s3 = s1.replace("ll", "kk");
    String s4 = s1.replace("ll", "kkkkk");
    
    System.out.println("s1:" + s1);//helloworld
    System.out.println("s2:" + s2);//hekkoworkd
    System.out.println("s3:" + s3);//hekkoworld
    System.out.println("s4:" + s4);//hekkkkkoworld
    
    //去除字符串兩端空格:String trim()
    String s5 = "         hello     world                  ";
    String s6 = s5.trim();
    System.out.println("s5:" + s5 + "---");
    System.out.println("s6:" + s6 + "---");
    
    //按字典順序比較兩個字符串(大小)
    String s7 = "hello";
    String s8 = "hfllo";
    String s9 = "gbc";
    String s10 = "xyz";
    System.out.println(s7.compareTo(s7));//0
    System.out.println(s7.compareTo(s8));//-1
    System.out.println(s7.compareTo(s9));//1
    System.out.println(s7.compareTo(s10));//-16
    
}

}it

相關文章
相關標籤/搜索