Java學習筆記98——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
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM