1. 程式人生 > 其它 >位元組 字元 字串 字串比較,查詢,替換,拆分,擷取

位元組 字元 字串 字串比較,查詢,替換,拆分,擷取

技術標籤:Java

提示:文章寫完後,目錄可以自動生成,如何生成可參考右邊的幫助文件

文章目錄


前言

Java中String類是比較常用的類,這裡整理一些String類中常用的的函式。

1.字元與字串

1.字元陣列->字串

    public static void main(String[] args) {
        char[] ch={'h','e','l','l','o'};
        String s1= new String(ch);
System.out.println(s1); }

2.將部分字元陣列變成字串

        char[] ch={'h','e','l','l','o'};
        String s1= new String(ch);
        System.out.println(s1);
        String s2=new String(ch,0,2);
        System.out.println(s2);

程式碼執行結果如下
在這裡插入圖片描述
3.再字串中取指定位置的字元

System.out.println(s1.charAt(1));

4.將字串變成字元陣列返回

char[] chars=s1.toCharArray();

2.位元組與字串

1.位元組陣列變成字串

        byte[] bytes={'w','o','r','l','d'};
        String s1=new String(bytes);

2.將字串以位元組陣列的形式返回

byte[] by=s1.getBytes();

3.字串比較

1.區分大小寫的比較(Boolean)

System.out.println(s1.equals(s2));

2.不區分大小寫的比較(Boolean)

System.out.println(s1.equalsIgnoreCase
(s2));

3.比較兩個字元的大小關係(int)

System.out.println(s1.compareTo(s2));

4.字串查詢

1.判斷一個子字串s2是否存在(boolean)

System.out.println(s1.contains(s2));

2.從頭開始查詢指定字串s2,查到了返回位置的開始下標,若查不到為-1(可有兩個引數,第二個可以指定開始查詢位置)(int)

System.out.println(s1.indexOf(s2));

3.從後往前查詢子字串位置,同上(int)

System.out.println(s1.lastIndexOf(s2));

4.判斷是否以指定字串開頭(可有兩個引數,第二個可以指定位置進行判斷)(boolean)

System.out.println(s1.startsWith(s2));

5.判斷是否以指定字串結尾(boolean)

System.out.println(s1.endsWith(s2));

5.字串替換

1.替換所有指定內容

s1.replaceAll("he",s2);

2.替換首個內容

s1.replaceFirst("he",s2);

6.字串拆分

將字串全部拆分(可有兩個引數,第二引數為陣列長度限制)

        String[] strings=s1.split(" ");
        String[] strings1=s1.split(" ",2);
        System.out.println(Arrays.toString(strings));
        System.out.println(Arrays.toString(strings1));

在這裡插入圖片描述

7.字串擷取(String)

從指定索引擷取到結尾(可以有兩個引數,第二個引數是擷取的末尾位置,左閉右開)

        s2=s1.substring(2);
        System.out.println(s2);
        s2=s1.substring(2,4);
        System.out.println(s2);