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