天天看點

Java 常用API之String、StringBuffer、StringBuilderString類StringBuffer類StringBuilder類

String類

public final class String
           

String類的特點

String表示字元串,他的值為不可更改的常量,在建立字元串後便不能更改。

記憶體中有專門的字元串緩沖區,同一個字元串可以被多個對象共享。

當我們建立字元串的時候Java會現在字元串緩沖區尋找有沒有相同的,有的話會直接指向他,沒有的話會建立一個新的字元串。

String是一種特殊的引用類型,預設值是:null。Java中所有的字元串都相當于是String的執行個體。

String類本身就重寫了toString()方法,是以直接列印一個空的字元串對象是不會輸出位址值而是什麼都不輸出。

字元串的拼接

字元串進行+運算的時候+号此時變為字元串拼接符。

public class Text {

	public static void main(String[] args) {
		String a = "hello";
		a += "word";
		System.out.println(a);
		String b = "Java";
		a += b;
		System.out.println(a);

	}
}
           

String類的構造方法

            String()

String的無參構造,初始化一個空的字元串對象。

            String(byte[ ] bytes)

将一個位元組數組通過ASCII碼解碼轉化成字元串:

public class Text {

	public static void main(String[] args) {
		byte[] arr={97,98,99,100,101,102};
		String s=new String(arr);
		System.out.println(s);       //abcdef

	}
}
           

            String(byte[] bytes, int offset, int length)

将一個位元組數組的一部分通過ASCII碼解碼轉化成字元串:

offset - 要解碼的第一個位元組的索引

length - 要解碼的位元組數

public class Text {

	public static void main(String[] args) {
		byte[] arr = { 97, 98, 99, 100, 101, 102 };
		String s = new String(arr, 1, 4);
		System.out.println(s);// bcde
	}
}
           

異常:IndexOutOfBoundsException,offset和 length指定的解碼範圍超出位元組數組的範圍。

            String(char[] value)

将字元數組轉化成字元串。

public class Text {

	public static void main(String[] args) {
		char[] arr = { '學', '習', 'J', 'A', 'V', 'A' };
		String s = new String(arr);
		System.out.println(s);// 學習JAVA

	}
}
           

            String(char[] value, int offset, int count)

将字元數組的一部分轉化成字元串。

offset - 初始偏移量

count - 長度

public class Text {

	public static void main(String[] args) {
		char[] arr = { '學', '習', 'J', 'A', 'V', 'A' };
		String s = new String(arr, 2, 4);
		System.out.println(s);// JAVA

	}
}
           

異常:IndexOutOfBoundsException,offset和 count參數的指定的範圍超出了字元數組的範圍。

            String(String original)

将參數中提供的字元串常量建立為一個新的字元串對象。

public static void main(String[] args) {
		String s = new String("abcdefg");
		String b="qwert";
		System.out.println(s);// abcdefg
		System.out.println(b);// qwert

	}
           

如上兩句,在實際使用中的效果是一樣的差別在于:

執行String s = new String("abcdefg");的時候現在堆記憶體中建立一個字元串對象,然後檢查字元串常量池中有沒有abcdefg有的話直接傳回位址值,沒有的話才會建立"abcdefg"。是以相當于建立了兩個對象,堆記憶體中一個常量池中一個。

而執行String b="qwert";的時候不在堆記憶體建立對象直接去檢查字元串常量池中有沒有qwert有的話直接傳回位址值,沒有的話建立"qwert"。是以僅在常量池中建立了一個對象。

String類中常用的方法

轉化功能

        toCharArray()

将字元串轉化為字元數組。

public class Text {

	public static void main(String[] args) {
		String b = "asdfgh";
		char []arr=b.toCharArray();
		for(int x=0;x<arr.length;x++) {
			System.out.println(arr[x]);
		}
	}
}
/**輸出為:
a
s
d
f
g
h
 */
           

        getBytes()

将字元串轉化為位元組數組,通過ASCII碼進行轉化。

public class Text {
	public static void main(String[] args) {
		String b = "hello123";
		byte []arr=b.getBytes();
		for(int x=0;x<arr.length;x++){
			System.out.print(arr[x]+", ");
		}
		
	}
}
/**
 * 輸出為:104, 101, 108, 108, 111, 49, 50, 51, 
 */
           

        valueOf(int i)

将int類型轉化成字元串。

public class Text {
	public static void main(String[] args) {
		int a=12345;
		String b=String.valueOf(a);
		System.out.println(b);	//12345
	}
}
           

這裡的valueOf方法是String類的靜态方法,通過類名調用使用:

public static String valueOf(int i) {
        return Integer.toString(i);
    }
           

valueOf方法有多個重載,支援任意類型基本資料類型轉化為字元串。

        toLowerCase()

将字元串轉化為小寫:

public class Text {
	public static void main(String[] args) {
		String a="HELLOWORD";
		System.out.println(a.toLowerCase());//helloword
	}
}
           

        toUpperCase()

将字元串轉化為大寫。

public class Text {
	public static void main(String[] args) {
		String a="helloword";
		System.out.println(a.toUpperCase());//HELLOWORD
	}
}
           

注意:大小寫轉化僅限于英文。

    split(String regex)

分割字元串,通過參數中指定的字元串,将一段字元串進行分割,傳回一個字元數組。參數支援正規表達式。

public class Test {
	public static void main(String[] args) {
		String s = "java=hello=google";
		String[] split = s.split("=");
		for (String ss : split) {
			System.out.println(ss);
		}
		/*
		 * java 
		 * hello 
		 * google
		 * 
		 */
	}
}
           

比較功能

        equals(Object anObject)

字元串中底層本身重寫了equals(Object anObject)方法,是以對字元串使用equals方法比較的是字元串的内容。傳回值是boolean類型。

public class Text {

	public static void main(String[] args) {
		String a = "java";
		String b = new String("java");
		String c = "hello";
		String d = "java";
		System.out.println(a == b);// false,因為位址不同
		System.out.println(a == d);// true,當常量池中已經有"java"再建立的時候會直接将位址指向過去,是以a和d的位址相同
		System.out.println(a.equals(b));// true,比較的是内容
		System.out.println(a.equals(c));// false

	}
}
           

        equalsIgnoreCase(String anotherString)

比較兩個字元串是否相等,忽略大小寫。傳回值為boolean類型

public class Text {

	public static void main(String[] args) {
		String a = "HELLOword";
		String b = "helloword";
		System.out.println(a.equalsIgnoreCase(b));// true
	}
}
           

        compareTo(String anotherString)

按字典順序比較兩個字元串。比較的是字元串中第一個字元的字典順序,如果在前傳回一個負值,在後傳回一個正值,相同傳回0。

傳回值的大小:

  • 兩個字元串首字母不同,則該方法傳回首字母的ASCII碼的內插補點。
  • 兩個字元串如果首字元相同,則比較下一個字元,直到有不同的為止,傳回該不同的字元的ASCII碼的內插補點。
  • 兩個字元串中短的字元串是長的字元串的開頭,則傳回兩個字元串的長度內插補點
public class Text {
	public static void main(String[] args) {
		String a = "abc";
		String c = "cbc";
		System.out.println(a.compareTo(c));// -2 首字母不同,傳回首字母的ASCII碼的內插補點。
		System.out.println(c.compareTo(a));// 2
		String b = "aec";
		System.out.println(a.compareTo(b));// -3 首字元相同,則比較下一個字元,直到有不同的為止,傳回該不同的字元的ASCII碼的內插補點。
		System.out.println(b.compareTo(a));// 3
		String d = "abcdefg";
		System.out.println(a.compareTo(d));// -4 短的字元串是長的字元串的開頭,則傳回兩個字元串的長度內插補點
		System.out.println(d.compareTo(a));// 4
	}
}
           

目前compareTo在實際開發中的的作用主要是比較軟體的版本号,因為版本号都是固定格式書寫,是以會輸出相差的版本數。

public class Text {
	public static void main(String[] args) {
		String a = "1.1.0";
		String b = "1.1.5";
		System.out.println(a.compareTo(b));// -5
	}
}
           

判斷功能

        contains(CharSequence s)

判斷一個字元串中是否包含另一個字元串,傳回值為boolean型,區分大小寫。

public class Text {
	public static void main(String[] args) {
		String b = "helloword大家好";
		System.out.println(b.contains("java"));//false
		System.out.println(b.contains("owo"));//true
	}
}
           

        startsWith(String prefix)

判斷目前字元串是否已給定字元串作為開頭,傳回值為boolean類型。

public class Text {
	public static void main(String[] args) {
		String b = "helloword大家好";
		System.out.println(b.startsWith("hello"));// true
		System.out.println(b.startsWith("java"));// false
	}
}
           

        endsWith(String suffix)

判斷目前字元串是否已給定字元串作為結尾,傳回值為boolean類型。

public class Text {
	public static void main(String[] args) {
		String b = "helloword大家好";
		System.out.println(b.startsWith("hel"));// true
		System.out.println(b.endsWith("大家好"));// true
	}
}
           

        isEmpty()

判斷字元串是否為空,傳回值為boolean類型

public class Text {
	public static void main(String[] args) {
		String b = "helloword大家好";
		String a = new String();
		System.out.println(b.isEmpty());// false
		System.out.println(a.isEmpty());// true
	}
}
           

查找功能

        length()

傳回此字元串的長度。

public class Text {

	public static void main(String[] args) {
		String b = "qwert";
		System.out.println(b.length());// 5
	}
}
           

需要注意在數組中沒有length()方法,隻有length屬性。

集合中沒有length(),擷取集合的元素數是:size()。

        charAt(int index)

傳回字元串中指定索引處的字元。計數從0開始。

public class Text {
	public static void main(String[] args) {
		String b = "helloword大家好";
		System.out.println(b.charAt(1));// e
		System.out.println(b.charAt(9));// 大
	}
}
           

異常:IndexOutOfBoundsException指定的索引超出字元串的長度範圍。

        indexOf(int ch)

查找指定字元第一次出現在目前字元串中的位置,計數從0開始。

注意這裡參數是int類型,填寫int類型查找的是對應ASCII碼中的字元。

public class Text {
	public static void main(String[] args) {
		String b = "hellowordilovejava";
		System.out.println(b.indexOf(97));//15
		System.out.println(b.indexOf('a'));//15
	}
}
           

        indexOf(int ch, int fromIndex)

從指定位置開始查找指定字元第一次出現的位置。

public class Text {
	public static void main(String[] args) {
		String b = "hellowordilovejavahellowordilovejava";
		System.out.println(b.indexOf('i'));// 9
		System.out.println(b.indexOf('i', 10));// 27
	}
}
           

        indexOf(String str)

查找指定字元串在目前字元串中第一次出現的索引,傳回值為int類型,計數從0開始。

public class Text {
	public static void main(String[] args) {
		String b = "hellowordilovejava";
		System.out.println(b.indexOf("word"));// 5
	}
}
           

        indexOf(String str, int fromIndex) 

從指定位置開始查找指定字元串第一次出現的位置,傳回值為int類型,計數從0開始。

public class Text {
	public static void main(String[] args) {
		String b = "hellowordilovejavahellowordilovejava";
		System.out.println(b.indexOf("love"));// 9
		System.out.println(b.indexOf("love", 11));// 27
	}
}
           

        substring(int beginIndex)

傳回從指定位置開始到結束的字元串。

public class Text {
	public static void main(String[] args) {
		String b = "hellowordilovejavahellowordilovejava";
		System.out.println(b.substring(5));    //wordilovejavahellowordilovejava
		System.out.println(b.substring(20));    //llowordilovejava
	}
}
           

        substring(int beginIndex, int endIndex)

截取從指定位置開始截取指定長度的字元串。

public class Text {
	public static void main(String[] args) {
		String b = "hellowordilovejava";
		System.out.println(b.substring(5, 9));//word
	}
}
           

注意:這裡有個包左不包右的原則,傳回的值包含5号位置的w,不包含9号位置的i。

替換功能

        replace(char oldChar, char newChar)

用指定字元替換字元串中的某個字元。

public class Text {
	public static void main(String[] args) {
		String a="helloword";
		System.out.println(a.replace('l', 'o'));//heoooword
	}
}
           

        replace(CharSequence target, CharSequence replacement)

用指定字元串替換字元串中的某段字元串。

public class Text {
	public static void main(String[] args) {
		String a="helloword";
		System.out.println(a.replace("owo","xxx"));//hellxxxrd
	}
}
           

        replaceAll(String regex,String replacement)

使用指定字元串替換給定字元串中滿足正規表達式的部分

public class Test04 {
	public static void main(String[] args) {
		String s = "hello12345World781323244454JavaEE";
		String n = s.replaceAll("\\d+", "*");// 替換所有的數字為*
		System.out.println(n);// hello*World*JavaEE

	}
}
           

        trim()

删除字元串兩端的空格

public class Text {
	public static void main(String[] args) {
		String a="  helloword  ";
		System.out.println(a);//  helloword  
		System.out.println(a.trim());//helloword
	}
}
           

        concat(String str)

和+拼接符效果一樣。

public class Text {
	public static void main(String[] args) {
		String b = "hello";
		String a = "word";
		System.out.println(b.concat(a));//helloword
	}
}  
           

String類例題:

    模拟一個登陸系統,可以從已注冊的使用者資訊中識别是哪位使用者的賬戶,并輸出這個賬戶的郵箱類型;登陸有4次機會,登陸失敗時候有對應的情況說明。

import java.util.Scanner;

class User {
    // 已經注冊的使用者資料
    private static String[] acc = { "[email protected]", "[email protected]", "[email protected]" };
    private static String[] pass = { "123456", "456789", "123789" };

    // 構造方法私有化,禁止建立該類的對象
    private User() {
        super();
    }

    // 賬戶驗證系統
    private static String verify(String ac, String pa) {
        if (ac.isEmpty() || pa.isEmpty()) {// 判斷使用者名或密碼是否為空
            return "賬戶或密碼不能為空";
        } else if (ac.endsWith(".com") && ac.contains("@")) {// 檢查輸入的賬戶是否包含@且以".com"結尾
            for (int i = 0; i < acc.length; i++) {
                if (acc[i].equals(ac)) {// 判斷賬戶是否為已注冊的賬戶
                    if (pass[i].equals(pa)) {// 判斷密碼是否輸入正确
                        return "恭喜你登陸成功";
                    } else {
                        return "密碼錯誤";
                    }
                }
            }
            return "該賬戶不存在";
        } else {
            return "使用者名格式不正确,必須為一個郵箱。檢查是否為[email protected]格式";
        }

    }

    // 登陸系統
    public static void login() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("請輸入使用者名(郵箱格式)");
            Scanner sc = new Scanner(System.in);
            String acc = sc.nextLine().trim().toLowerCase();// trim方法删除輸入時兩端的空格防止影響判斷
            // toLowerCase方法将輸入内容全部轉化為小寫,目的是輸入的賬戶不區分大小寫,一般郵箱賬戶沒有大小寫區分規則。
            System.out.println("請輸入密碼");
            Scanner sc2 = new Scanner(System.in);
            String pas = sc2.nextLine().trim();//密碼中區分大小寫是以不需要toLowerCase
            if (i <= 4) {
                String res = User.verify(acc, pas);// 調用賬戶驗證系統
                System.out.print(res);// 輸出驗證結果
                if (res.startsWith("恭喜你")) {// 查找驗證結果是否以"恭喜你"開頭
                    System.out.print(",您使用的郵箱是:");
                    int temp = acc.indexOf('@');// 查找@所在位置的下标
                    String tempstr = acc.substring(temp);// 截取@以後包含@的字元串
                    switch (tempstr) {
                    case "@qq.com":
                        System.out.println("QQ郵箱");
                        break;
                    case "@163.com":
                        System.out.println("網易163郵箱");
                        break;
                    case "@gmail.com":
                        System.out.println("Google郵箱");
                        break;
                    }
                    break;
                } else {
                    if (4 - i == 0) {// 判斷嘗試登陸次數是否用盡還沒有登陸成功
                        System.out.println(",登陸機會用盡,請聯系背景管了解鎖");
                        break;
                    } else {

                        System.out.println(",您還有" + (4 - i) + "次登陸機會");
                    }
                }
            }
        }
    }
}

public class Text {
    public static void main(String[] args) {
        User.login();
    }
}
/**
請輸入使用者名(郵箱格式)
[email protected]
請輸入密碼

賬戶或密碼不能為空,您還有3次登陸機會
請輸入使用者名(郵箱格式)
123456qq.com
請輸入密碼
123456
使用者名格式不正确,必須為一個郵箱。檢查是否為[email protected]格式,您還有2次登陸機會
請輸入使用者名(郵箱格式)
[email protected]
請輸入密碼
123458
密碼錯誤,您還有1次登陸機會
請輸入使用者名(郵箱格式)
[email protected]
請輸入密碼
123456
恭喜你登陸成功,您使用的郵箱是:QQ郵箱
 */
           

StringBuffer類

特點

  • 線程安全,可變的字元序列。字元串緩沖區和String一樣但是可以修改。
  • StringBuffer可以安全地被多個線程使用。會在必要的時候進行同步。
  • 底層實作方式為位元組數組。

構造方法

        StringBuffer()

構造一個空的的字元串緩沖區,初始容量為16個字元。

        StringBuffer(int capacity)

指定容量,構造一個空的的字元串緩沖區。如果知道最終需要的長度建議優先使用。

        StringBuffer(String str)

構造一個以指定字元串為内容的字元串緩沖區。

常用的方法

查詢

        length()

傳回字元序列的長度,傳回值為int型。

        capacity()

傳回目前字元序列的容量。

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer();
		System.out.println(">>" + s);// >>
		// 此時是個空字元串
		System.out.println(s.length());// 0
		System.out.println(s.capacity());// 16
		// 預設容量16個字元
		s = new StringBuffer("java");
		System.out.println(">>" + s);// >>java
		System.out.println(s.length());// 4
		System.out.println(s.capacity());// 20
		// 系統動态配置設定容量
	}
}
           

需要注意以下寫法不正确:

//StringBuffer s = new StringBuffer();
		//s="java";
           

不能直接将一個字元串指派給字元序列,需要通過構造方法指派。

添加

        append()

     将指定内容追加到字元序列的後面,append有多種重載方法,支援任意類型轉化為字元串然後追加到字元序列最後。

class Text {
	int i;
	public Text(int i) {
		super();
		this.i = i;
	}
}

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer();
		s.append("hello");// 字元串
		s.append(123);// int類型
		s.append('w');// 字元
		s.append(true);// Boolean類型
		s.append(3.14);// float類型
		char[] arr = { 'A', 'B', 'C' };
		s.append(arr);// 字元數組
		Text t = new Text(200);
		s.append(t.i);// 引用類型
		System.out.println(s);// hello123wtrue3.14ABC200
	}
}
           

        insert(int offset, String str)

将指定字元串添加到字元序列的指定位置,傳回值是字元序列本身。

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hellojava");
		s.insert(5, "word");
		System.out.println(s);// hellowordjava
	}
}
           

删除

        deleteCharAt(int index)

删除字元序列中指定位置的字元

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hellojava");
		s.deleteCharAt(5);
		System.out.println(s);// helloava
	}
}
           

        delete(int start, int end)

删除字元序列中指定位置的字元串,同樣存在包左不包右的原則。

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hellojava");
		s.delete(2, 5);
		System.out.println(s);// hejava
	}
}
           

排序

        reverse()

反轉目前字元序列,傳回值是字元序列本身

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hellojava");
		s.reverse();
		System.out.println(s);// avajolleh
	}
}
           

截取

        substring(int start)

從指定位置開始截取到結束,傳回值是一個新的字元串。

        substring(int start, int end)

從指定位置開始截取到指定位置結束,傳回值是一個新的字元串,遵循包左不包右。

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hellowordjava");
		System.out.println(s.substring(5));// wordjava
		System.out.println(s.substring(5, 9));// word

	}
}
           

替換

        replace(int start, int end, String str)

從指定位置開始到指定位置結束,替換為指定字元串。傳回值是字元序列本身。

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hellowordjava");
		s.replace(5, 9, "Student");
		System.out.println(s);//helloStudentjava
	}
}
           

轉化

        toString()

将字元序列轉化成字元串;

public class buffer {
	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("hellowordjava");
		String sr=s.toString();
		System.out.println(sr);//hellowordjava
	}
}
           

轉化的作用是有時候我們需要使用到String裡面的方法

例題

編寫一個可以判斷輸入内容是否為對稱字元串的方法

import java.util.Scanner;

public class buffer {

	public static void main(String[] args) {
		System.out.println("請輸入");
		Scanner sc = new Scanner(System.in);

		if (reversal(sc.nextLine())) {
			System.out.println("輸入的内容對稱");
		} else {
			System.out.println("輸入的内容不對稱");
		}
	}

	private static boolean reversal(String a) {
		return new StringBuffer(a).reverse().toString().equals(a);
		// 鍊式程式設計new StringBuffer(a)将輸入的字元串轉化為字元串序列
		// reverse()反轉
		// toString()轉換成String類型
		// equals(a)與輸入字元串進行對比
	}

}
           

StringBuilder類

此類提供與StringBuffer相同的方法,但不保證同步,缺乏安全性,不能安全使用多線程。但是速度要快得多。

StringBuffer、StringBuilder和Straight的差別

StringBuffer StringBuilder Straight
可變字元序列,相當于容器 可變字元序列,相當于容器 不可變的字元序列
修改StringBuffer,舊的字元串會被清理掉 每次對String改變都相當于建立新的字元串,比較耗費記憶體。
線程安全的且同步的,執行效率低 線程不安全的且不同步的,執行效率高,單線程優先采用。

StringBuffer和數組的差別

StringBuffer 數組
隻能在字元串緩沖區儲存字元串的容器 存儲多個資料的容器,并且多個資料的類型必須一緻
擷取緩沖區的長度:length() 計算數組長度功能:length屬性