1. 程式人生 > 其它 >Java學習筆記97——String類的替換功能

Java學習筆記97——String類的替換功能

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 StringDemo11 {
  public static void main(String[] args) {
    String s = "helloworldowodadadwowo";
​
    //String replace(char old,char new)
    //將新的字元替換字元中指定的所有字元,並返回新的字串
    String s1 = s.replace('l', 'a');//將l替換為a
    System.out.println(s1);
    System.out.println(s);
​
    System.out.println("******************************");
    //String replace(String old,String new)
    //將字串中舊的小串用新的小串替換,返回一個新的字串
    String s2 = s.replace("owo", "wow");//將owo替換為wow
    System.out.println(s2);
​
    String s3 = s.replace("owo", "qwerdf");
    System.out.println(s3);
​
    //如果被替換的字串不存在,返回的是原本的字串
    String s4 = s.replace("qwer", "poiu");
    System.out.println(s4);
​
    System.out.println("***********************************");
    //String trim() 去除字串兩邊的空格
    String s5 = " hello world ";
    System.out.println(s5);
    System.out.println(s5.trim());//"hello world"(中間的空格不刪)
​
    System.out.println("***********************************");
    //int compareTo(String str)
    String s6 = "hello"; //h的ASCII碼值104
    String s7 = "hello";
    String s8 = "abc"; //a的ASCII碼值97
    String s9 = "qwe"; //q的ASCII碼值113
    System.out.println(s6.compareTo(s7)); //0
    System.out.println(s6.compareTo(s8)); //7
    System.out.println(s6.compareTo(s9)); //-9
​
    String s10 = "hel";
    System.out.println(s6.compareTo(s10)); //2
   }
}