天天看點

【Java】字元串操作彙總,equals與==差別

字元串建立方法

/*
java.lang.String類代表字元串。
API當中說:Java 程式中的所有字元串字面值(如 "abc" )都作為此類的執行個體實作。
其實就是說:程式當中所有的雙引号字元串,都是String類的對象。(就算沒有new,也照樣是。)

字元串的特點:
1. 字元串的内容永不可變。【重點】
2. 正是因為字元串不可改變,是以字元串是可以共享使用的。
3. 字元串效果上相當于是char[]字元數組,但是底層原理是byte[]位元組數組。

建立字元串的常見3+1種方式。
三種構造方法:
public String():建立一個空白字元串,不含有任何内容。
public String(char[] array):根據字元數組的内容,來建立對應的字元串。
public String(byte[] array):根據位元組數組的内容,來建立對應的字元串。
一種直接建立:
String str = "Hello"; // 右邊直接用雙引号

注意:直接寫上雙引号,就是字元串對象。
 */
public class Demo01String {

    public static void main(String[] args) {
        // 使用空參構造
        String str1 = new String(); // 小括号留白,說明字元串什麼内容都沒有。
        System.out.println("第1個字元串:" + str1);

        // 根據字元數組建立字元串
        char[] charArray = { 'A', 'B', 'C' };
        String str2 = new String(charArray);
        System.out.println("第2個字元串:" + str2);

        // 根據位元組數組建立字元串
        byte[] byteArray = { 97, 98, 99 };
        String str3 = new String(byteArray);
        System.out.println("第3個字元串:" + str3);

        // 直接建立
        String str4 = "Hello";
        System.out.println("第4個字元串:" + str4);
    }

}      

字元串常量池

/*
字元串常量池:程式當中直接寫上的雙引号字元串,就在字元串常量池中。

對于基本類型來說,==是進行數值的比較。
對于引用類型來說,==是進行【位址值】的比較。
 */
public class Demo02StringPool {

    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "abc";

        char[] charArray = {'a', 'b', 'c'};
        String str3 = new String(charArray);

        System.out.println(str1 == str2); // true
        System.out.println(str1 == str3); // false
        System.out.println(str2 == str3); // false
    }
}      
【Java】字元串操作彙總,equals與==差別

==與equals

equals是對内容進行比較

/*
==是進行引用類型(如對象類型)的位址值比較,如果确實需要字元串(JAVA中字元串也是對象,屬于引用類型)的内容比較,可以使用兩個方法:

public boolean equals(Object obj):參數可以是任何對象,隻有參數是一個字元串并且内容相同的才會給true;否則傳回false。
注意事項:
1. 任何對象都能用Object進行接收。
2. equals方法具有對稱性,也就是a.equals(b)和b.equals(a)效果一樣。
3. 如果比較雙方一個常量一個變量,推薦把常量字元串寫在前面。
推薦:"abc".equals(str)    不推薦:str.equals("abc")

public boolean equalsIgnoreCase(String str):忽略大小寫,進行内容比較。
 */
public class Demo01StringEquals {

    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};
        String str3 = new String(charArray);

        System.out.println(str1.equals(str2)); // true
        System.out.println(str2.equals(str3)); // true
        System.out.println(str3.equals("Hello")); // true
        System.out.println("Hello".equals(str1)); // true

        String str4 = "hello";
        System.out.println(str1.equals(str4)); // false
        System.out.println("=================");

        String str5 = null;
        System.out.println("abc".equals(str5)); // 推薦:false
//        System.out.println(str5.equals("abc")); // 不推薦:報錯,空指針異常NullPointerException
        System.out.println("=================");
        
        String strA = "Java";
        String strB = "java";
        System.out.println(strA.equals(strB)); // false,嚴格區分大小寫
        System.out.println(strA.equalsIgnoreCase(strB)); // true,忽略大小寫
        // 注意,隻有英文字母區分大小寫,其他都不區分大小寫
        System.out.println("abc一123".equalsIgnoreCase("abc壹123")); // false
    }
}      

String當中與擷取相關的常用方法

/*
String當中與擷取相關的常用方法有:

public int length():擷取字元串當中含有的字元個數,拿到字元串長度。
public String concat(String str):将目前字元串和參數字元串拼接成為傳回值新的字元串。
public char charAt(int index):擷取指定索引位置的單個字元。(索引從0開始。)
public int indexOf(String str):查找參數字元串在本字元串當中首次出現的索引位置,如果沒有傳回-1值。
 */
public class Demo02StringGet {

    public static void main(String[] args) {
        // 擷取字元串的長度
        int length = "asdasfeutrvauevbueyvb".length();
        System.out.println("字元串的長度是:" + length);

        // 拼接字元串
        String str1 = "Hello";
        String str2 = "World";
        String str3 = str1.concat(str2);
        System.out.println(str1); // Hello,原封不動
        System.out.println(str2); // World,原封不動
        System.out.println(str3); // HelloWorld,新的字元串
        System.out.println("==============");

        // 擷取指定索引位置的單個字元
        char ch = "Hello".charAt(1);
        System.out.println("在1号索引位置的字元是:" + ch);
        System.out.println("==============");

        // 查找參數字元串在本來字元串當中出現的第一次索引位置
        // 如果根本沒有,傳回-1值
        String original = "HelloWorldHelloWorld";
        int index = original.indexOf("llo");
        System.out.println("第一次索引值是:" + index); // 2
        System.out.println("HelloWorld".indexOf("abc")); // -1
    }
}      

字元串截取的方法

/*
字元串的截取方法:

public String substring(int index):截取從參數位置一直到字元串末尾,傳回新字元串。
public String substring(int begin, int end):截取從begin開始,一直到end結束,中間的字元串。
備注:[begin,end),包含左邊,不包含右邊。
 */
public class Demo03Substring {

    public static void main(String[] args) {
        String str1 = "HelloWorld";
        String str2 = str1.substring(5);
        System.out.println(str1); // HelloWorld,原封不動
        System.out.println(str2); // World,新字元串
        System.out.println("================");

        String str3 = str1.substring(4, 7);
        System.out.println(str3); // oWo
        System.out.println("================");

        // 下面這種寫法,字元串的内容仍然是沒有改變的
        // 下面有兩個字元串:"Hello","Java"
        // strA當中儲存的是位址值。
        // 本來位址值是Hello的0x666,
        // 後來位址值變成了Java的0x999
        String strA = "Hello";
        System.out.println(strA); // Hello
        strA = "Java";
        System.out.println(strA); // Java
    }
}      

String當中與轉換相關的常用方法

/*
String當中與轉換相關的常用方法有:

public char[] toCharArray():将目前字元串拆分成為字元數組作為傳回值。
public byte[] getBytes():獲得目前字元串底層的位元組數組。
public String replace(CharSequence oldString, CharSequence newString):
将所有出現的老字元串替換成為新的字元串,傳回替換之後的結果新字元串。
備注:CharSequence意思就是說可以接受字元串類型。
 */
public class Demo04StringConvert {

    public static void main(String[] args) {
        // 轉換成為字元數組
        char[] chars = "Hello".toCharArray();
        System.out.println(chars[0]); // H
        System.out.println(chars.length); // 5
        System.out.println("==============");

        // 轉換成為位元組數組
        byte[] bytes = "abc".getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println("==============");

        // 字元串的内容替換
        String str1 = "How do you do?";
        String str2 = str1.replace("o", "*");
        System.out.println(str1); // How do you do?
        System.out.println(str2); // H*w d* y*u d*?
        System.out.println("==============");

        String lang1 = "會不會玩兒呀!你大爺的!你大爺的!你大爺的!!!";
        String lang2 = lang1.replace("你大爺的", "****");
        System.out.println(lang2); // 會不會玩兒呀!****!****!****!!!
    }
}      

分割字元串的方法

/*
分割字元串的方法:
public String[] split(String regex):按照參數的規則,将字元串切分成為若幹部分。

注意事項:
split方法的參數其實是一個“正規表達式”,今後學習。
今天要注意:如果按照英文句點“.”進行切分,必須寫"\\."(兩個反斜杠)
 */
public class Demo05StringSplit {

    public static void main(String[] args) {
        String str1 = "aaa,bbb,ccc";
        String[] array1 = str1.split(",");
        for (int i = 0; i < array1.length; i++) {
            System.out.println(array1[i]);
        }
        System.out.println("===============");

        String str2 = "aaa bbb ccc";
        String[] array2 = str2.split(" ");
        for (int i = 0; i < array2.length; i++) {
            System.out.println(array2[i]);
        }
        System.out.println("===============");

        String str3 = "XXX.YYY.ZZZ";
        String[] array3 = str3.split("\\.");
        System.out.println(array3.length); // 0
        for (int i = 0; i < array3.length; i++) {
            System.out.println(array3[i]);
        }
    }
}      

練習1

/*
題目:
定義一個方法,把數組{1,2,3}按照指定格式拼接成一個字元串。格式參照如下:[word1#word2#word3]。

分析:
1. 首先準備一個int[]數組,内容是:1、2、3
2. 定義一個方法,用來将數組變成字元串
三要素
傳回值類型:String
方法名稱:fromArrayToString
參數清單:int[]
3. 格式:[word1#word2#word3]
用到:for循環、字元串拼接、每個數組元素之前都有一個word字樣、分隔使用的是#、區分一下是不是最後一個
4. 調用方法,得到傳回值,并列印結果字元串
 */
public class string_exersice {
    //把{1,2,3}拼接成字元串[world1#world2#world3]
    public static void main(String[] args) {
        int[] a1 = {1, 2, 3};
        String res2 = fromArrayToString(a1);
        System.out.println(res2);
    }

    public static String fromArrayToString(int[] a1) {
        String res = "";
        for (int i = 0; i < a1.length; i++) {
            if (i == a1.length - 1) {
                //res = res.concat("world" + a1[i]);
                res+="world"+a1[i];
            } else {
                res = res.concat("world" + a1[i] + "#");
            }
        }
        return res;
    }
}      

練習2

/*
題目:
鍵盤輸入一個字元串,并且統計其中各種字元出現的次數。
種類有:大寫字母、小寫字母、數字、其他

思路:
1. 既然用到鍵盤輸入,肯定是Scanner
2. 鍵盤輸入的是字元串,那麼:String str = sc.next();
3. 定義四個變量,分别代表四種字元各自的出現次數。
4. 需要對字元串一個字、一個字檢查,String-->char[],方法就是toCharArray()
5. 周遊char[]字元數組,對目前字元的種類進行判斷,并且用四個變量進行++動作。
6. 列印輸出四個變量,分别代表四種字元出現次數。
 */
public class Demo07StringCount {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入一個字元串:");
        String input = sc.next(); // 擷取鍵盤輸入的一個字元串

        int countUpper = 0; // 大寫字母
        int countLower = 0; // 小寫字母
        int countNumber = 0; // 數字
        int countOther = 0; // 其他字元

        char[] charArray = input.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            char ch = charArray[i]; // 目前單個字元
            if ('A' <= ch && ch <= 'Z') {
                countUpper++;
            } else if ('a' <= ch && ch <= 'z') {
                countLower++;
            } else if ('0' <= ch && ch <= '9') {
                countNumber++;
            } else {
                countOther++;
            }
        }
        System.out.println("大寫字母有:" + countUpper);
        System.out.println("小寫字母有:" + countLower);
        System.out.println("數字有:" + countNumber);
        System.out.println("其他字元有:" + countOther);
    }
}