字符串中的截取,分割,轉換方法



/*
字符串的截取方法(根據一個大字符串,截取得到小字符串,其中一部分)

public String substring(int beginIndex):截取字符串,從指定的索引位置一直到字符串末尾。
public String substring(int beginIndex, int endIndex):截取字符串,從指定的開始索引,一直到指定的結束索引。
兩個參數的方法,左閉右開區間,包含左邊,不包含右邊。
 */

public class Demo05Substring {

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

        String str2 = str1.substring(5);
        System.out.println(str1); // HelloWorld
        System.out.println(str2); // World

        String str3 = str1.substring(5, 8);
        System.out.println(str3); // Wor
    }}

/*
字符串的分割方法:
public String[] split(String regex):根據參數爲標準,切割成爲若干段兒字符串,也就是字符串數組。

參數regex其實代表“正則表達式”,這是一種用來描述規則的規範。
如果希望用英文句點進行切分,那麼參數必須寫成"\\.",這是一個特例。
因爲英文句點在正則表達式當中有特殊含義。
 */
public class Demo07StringSplit {

    public static void main(String[] args) {
        String strA = "aaa,bbb,ccc";

        String[] arrayA = strA.split(",");
        for (int i = 0; i < arrayA.length; i++) {
            System.out.println(arrayA[i]); //
        }
        System.out.println("============");

        String strB = "XXX OOO XXX";
        String[] arrayB = strB.split(" ");
        for (int i = 0; i < arrayB.length; i++) {
            System.out.println(arrayB[i]);
        }
        System.out.println("============");

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

}

package cn.itcast.day08.demo01;

/*
字符串當中與轉換相關的方法:
public char[] toCharArray():將字符串拆分成爲字符數組
public byte[] getBytes():將字符串轉換成爲底層的字節數組
public String replace(CharSequence target, CharSequence replacement):將字符串當中指定的內容,全都替換成爲新內容。

 */
public class Demo06StringConvert {

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

        // 拆分成爲字符數組
        char[] chars = str1.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
        System.out.println("=============");

        // 拆分成爲字節數組
        byte[] bytes = str1.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println("=============");

        // 替換
        String str2 = "How do you do?";
        String str3 = str2.replace("o", "*");
        System.out.println(str2); // How do you do?
        System.out.println(str3); // H*w d* y*u d*?
        System.out.println("=============");

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

}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章