五、String类的其他功能

来源:互联网 发布:java字符串长度函数 编辑:程序博客网 时间:2024/04/29 04:38
/* * 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) {// 替换功能String s1 = "helloworld";String s2 = s1.replace('l', 'k');String s3 = s1.replace("owo", "ak47");System.out.println("s1:" + s1);System.out.println("s2:" + s2);System.out.println("s3:" + s3);System.out.println("---------------");// 去除字符串两空格String s4 = " hello world  ";String s5 = s4.trim();System.out.println("s4:" + s4 + "---");System.out.println("s5:" + s5 + "---");// 按字典顺序比较两个字符串String s6 = "hello";String s7 = "hello";String s8 = "abc";String s9 = "xyz";System.out.println(s6.compareTo(s7));// 0System.out.println(s6.compareTo(s8));// 7System.out.println(s6.compareTo(s9));// -16}}
/* * 如果我们看到问题了,看怎么办呢? * 看源码。 */public class StringTest {public static void main(String[] args) {String s1 = "hello";String s2 = "hel";System.out.println(s1.compareTo(s2)); // 2}}
  private final char value[];      字符串会自动转换为一个字符数组。    public int compareTo(String anotherString) {  //this -- s1 -- "hello"  //anotherString -- s2 -- "hel"          int len1 = value.length; //this.value.length--s1.toCharArray().length--5        int len2 = anotherString.value.length;//s2.value.length -- s2.toCharArray().length--3        int lim = Math.min(len1, len2); //Math.min(5,3); -- lim=3;        char v1[] = value; //s1.toCharArray()        char v2[] = anotherString.value;                //char v1[] = {'h','e','l','l','o'};        //char v2[] = {'h','e','l'};        int k = 0;        while (k < lim) {            char c1 = v1[k]; //c1='h','e','l'            char c2 = v2[k]; //c2='h','e','l'            if (c1 != c2) {                return c1 - c2;            }            k++;        }        return len1 - len2; //5-3=2;   }      String s1 = "hello";   String s2 = "hel";   System.out.println(s1.compareTo(s2)); // 2



0 0