java.lang.String 使用介紹


這里我們將總結字符串相關的知識,除了總結String的API用法,同時我們還會總結一些相關的知識點,包括字符串常量池、StringBuffer、StringBuilder,以及equals和==的用法。

一、String的用法

String類在java.lang包中,java使用String類創建一個字符串變量,字符串變量屬於對象。java把String類聲明的final類,不能有子類。String類對象創建后不能修改,由0或多個字符組成,包含在一對雙引號之間,下面簡單的熟悉一下其常用的API

 java.lang.String  
  
 char charAt (int index)     返回index所指定的字符  
 String concat(String str) 將兩字符串連接 boolean endsWith(String str) 測試字符串是否以str結尾 boolean equals(Object obj) 比較兩對象 char[] getBytes 將字符串轉換成字符數組返回 char[] getBytes(String str) 將指定的字符串轉成制服數組返回 boolean startsWith(String str) 測試字符串是否以str開始 int length() 返回字符串的長度 String replace(char old ,char new) 將old用new替代 char[] toCharArray 將字符串轉換成字符數組 String toLowerCase() 將字符串內的字符改寫成小寫 String toUpperCase() 將字符串內的字符改寫成大寫 String valueOf(Boolean b) 將布爾方法b的內容用字符串表示 String valueOf(char ch) 將字符ch的內容用字符串表示 String valueOf(int index) 將數字index的內容用字符串表示 String valueOf(long l) 將長整數字l的內容用字符串表示 String substring(int1,int2) 取出字符串內第int1位置到int2的字符串 
1.構造方法
//直接初始化 String str = "abc"; //使用帶參構造方法初始化 char[] char = {'a','b','c'}; String str1 = new String("abc");String str2 = new String(str); String str3 = new String(char); 
2.求字符串長度和某一位置字符
String str = new String("abcdef"); int strlength = str.length();//strlength = 7 char ch = str.charAt(4);//ch = e 
3.提取子串

用String類的substring方法可以提取字符串中的子串,該方法有兩種常用參數: 1)public String substring(int beginIndex)//該方法從beginIndex位置起,從當前字符串中取出剩余的字符作為一個新的字符串返回。 2)public String substring(int beginIndex, int endIndex)//該方法從beginIndex位置起,從當前字符串中取出到endIndex-1位置的字符作為一個新的字符串返回。

String str1 = new String("abcdef"); String str2 = str1.substring(2);//str2 = "cdef" String str3 = str1.substring(2,5);//str3 = "cde" 
4.字符串比較

1)public int compareTo(String anotherString)//該方法是對字符串內容按字典順序進行大小比較,通過返回的整數值指明當前字符串與參數字符串的大小關系。若當前對象比參數大則返回正整數,反之返回負整數,相等返回0。 2)public int compareToIgnoreCase(String anotherString)//與compareTo方法相似,但忽略大小寫。 3)public boolean equals(Object anotherObject)//比較當前字符串和參數字符串,在兩個字符串相等的時候返回true,否則返回false。 4)public boolean equalsIgnoreCase(String anotherString)//與equals方法相似,但忽略大小寫。

String str1 = new String("abc"); String str2 = new String("ABC"); int a = str1.compareTo(str2);//a>0 int b = str1.compareToIgnoreCase(str2);//b=0 boolean c = str1.equals(str2);//c=false boolean d = str1.equalsIgnoreCase(str2);//d=true 
5.字符串鏈接

public String concat(String str)//將參數中的字符串str連接到當前字符串的后面,效果等價於"+"

String str = "aa".concat("bb").concat("cc"); //相當於String str = "aa"+"bb"+"cc"; 
6.字符串中單個字符查找

1)public int indexOf(int ch/String str)//用於查找當前字符串中字符或子串,返回字符或子串在當前字符串中從左邊起首次出現的位置,若沒有出現則返回-1。 2)public int indexOf(int ch/String str, int fromIndex)//改方法與第一種類似,區別在於該方法從fromIndex位置向后查找。 3)public int lastIndexOf(int ch/String str)//該方法與第一種類似,區別在於該方法從字符串的末尾位置向前查找。 4)public int lastIndexOf(int ch/String str, int fromIndex)//該方法與第二種方法類似,區別於該方法從fromIndex位置向前查找。

String str = "I really miss you !"; int a = str.indexOf('a');//a = 4 int b = str.indexOf("really");//b = 2 int c = str.indexOf("gg",2);//c = -1 int d = str.lastIndexOf('s');//d = 6 int e = str.lastIndexOf('s',7);//e = 7 
7.大小寫轉換

1)public String toLowerCase()//返回將當前字符串中所有字符轉換成小寫后的新串 2)public String toUpperCase()//返回將當前字符串中所有字符轉換成大寫后的新串

String str = new String("abCD"); String str1 = str.toLowerCase();//str1 = "abcd" String str2 = str.toUpperCase();//str2 = "ABCD" 
8.字符串中字符的替換

1)public String replace(char oldChar, char newChar)//用字符newChar替換當前字符串中所有的oldChar字符,並返回一個新的字符串。 2)public String replaceFirst(String regex, String replacement)//該方法用字符replacement的內容替換當前字符串中遇到的第一個和字符串regex相匹配的子串,應將新的字符串返回。 3)public String replaceAll(String regex, String replacement)//該方法用字符replacement的內容替換當前字符串中遇到的所有和字符串regex相匹配的子串,應將新的字符串返回。

String str = "asdzxcasd"; String str1 = str.replace('a','g');//str1 = "gsdzxcgsd" String str2 = str.replace("asd","fgh");//str2 = "fghzxcfgh" String str3 = str.replaceFirst("asd","fgh");//str3 = "fghzxcasd" String str4 = str.replaceAll("asd","fgh");//str4 = "fghzxcfgh" 
9.其他方法

1)String trim()//截去字符串兩端的空格,但對於中間的空格不處理。

String str = " a bc "; String str1 = str.trim(); int a = str.length();//a = 6 int b = str1.length();//b = 4 

2)boolean statWith(String prefix)boolean endWith(String suffix)//用來比較當前字符串的起始字符或子字符串prefix和終止字符或子字符串suffix是否和當前字符串相同,重載方法中同時還可以指定比較的開始位置offset。

String str = "abcdef"; boolean a = str.statWith("ab");//a = true boolean b = str.endWith("ef");//b = true 

3)contains(String str)//判斷參數s是否被包含在字符串中,並返回一個布爾類型的值。

String str = "abcdef"; str.contains("ab");//true str.contains("gh");//false 

4)String[] split(String str)//將str作為分隔符進行字符串分解,分解后的字字符串在字符串數組中返回。

String str = "abc def ghi"; String[] str1 = str.split(" ");//str1[0] = "abc";str1[1] = "def";str1[2] = "ghi"; 
10.類型轉換
  • 字符串轉基本類型 java.lang包中有Byte、Short、Integer、Float、Double類的調用方法:
    • public static byte parseByte(String s)
    • public static short parseShort(String s)
    • public static short parseInt(String s)
    • public static long parseLong(String s)
    • public static float parseFloat(String s)
    • public static double parseDouble(String s)
int n = Integer.parseInt("12"); float f = Float.parseFloat("12.34"); double d = Double.parseDouble("1.124"); 
  • 基本類型轉字符串 String類中提供了String valueOf()放法,用作基本類型轉換為字符串類型
    • static String valueOf(char data[])
    • static String valueOf(char data[], int offset, int count)
    • static String valueOf(boolean b)
    • static String valueOf(char c)
    • static String valueOf(int i)
    • static String valueOf(long l)
    • static String valueOf(float f)
    • static String valueOf(double d)
//將char '8' 轉換為int 8 String str = String.valueOf('8'); int num = Integer.parseInt(str); 
  • 進制轉換 使用Long類中的方法得到整數之間的各種進制轉換的方法:
    • Long.toBinaryString(long l)//二進制
    • Long.toOctalString(long l)//十進制
    • Long.toHexString(long l)//十六進制
    • Long.toString(long l, int p)//p作為任意進制

二、String特性

這一部分介紹String的一些特性,涉及到字符串常量池String.intern()以及我們經常遇到的“==”“equals()”問題。 下面我們將通過不同的例子來解釋:

例子1:
String a = "Hello World!"; String b = "Hello World!"; String c = new String("Hello World!"); String d = "Hello"+" "+"World!"; System.out.println(a == b);//true System.out.println(a == c);//false System.out.println(a == d);//true 

我們應該明白:

  • 首先String不屬於8種基本數據類型,String是一個對象。 因為對象的默認值是null,所以String的默認值也是null;但它又是一種特殊的對象,有其它對象沒有的一些特性。
  • 在這里,我們先不談堆,也不談棧,只先簡單引入常量池這個簡單的概念。 常量池(constant pool)指的是在編譯期被確定,並被保存在已編譯的.class文件中的一些數據。它包括了關於類、方法、接口等中的常量,也包括字符串常量。
  • Java會確保一個字符串常量只有一個拷貝。 因為例子中的a和b都是字符串常量,它們在編譯期就被確定了,所以 a==b為true;而"Hello"和" "以及"World!"也都是字符串常量,當一個字符串由多個字符串常量連接而成時,它自己肯定也是字符串常量,所以d也同樣在編譯期就被解析為一個字符串常量,所以d也是常量池中"Hello World!"的一個引用。所以我們得出a==b==d; 用new String() 創建的字符串不是常量,不能在編譯期就確定,所以new String()創建的字符串不放入常量池中,它們有自己的地址空間。
例子2:
String a = "HelloWorld"; String b = new String("HelloWorld"); String c = "Hello"+ new String("World"); System.out.println( a == b );//false System.out.println( a == c );//false System.out.println( b == c );//false 

例子2中a還是常量池中”HelloWorld”的引用,b因為無法在編譯期確定,所以是運行時創建的新對象”HelloWorld”的引用,c因為有后半部分new String(“World”)所以也無法在編譯期確定,所以也是一個新創建對象”HelloWorld”的引用,明白了這些也就知道為何得出此結果了。 **PS: ** String.intern(): 再補充介紹一點:存在於.class文件中的常量池,在運行期被JVM裝載,並且可以擴充。String的intern()方法就是擴充常量池的一個方法;當一個String實例str調用intern()方法時,Java查找常量池中是否有相同Unicode的字符串常量,如果有,則返回其的引用,如果沒有,則在常量池中增加一個Unicode等於str的字符串並返回它的引用,看例3就清楚了。

例子3:
String a = "Hello"; String b = new String("Hello"); String c = new String("Hello"); System.out.println( a == b );//false System.out.println( “**********” ); b.intern(); c = c.intern(); //把常量池中"Hello"的引用賦給c System.out.println( a == b);//false雖然執行了b.intern()但沒有賦值給b System.out.println( a == b.intern() );//true System.out.println( a == c ); //true 
例子4:

關於equals()和==: equals()是比較兩個對象的值是否相等,這個對於String簡單來說就是比較兩字符串的Unicode序列是否相當,如果相等返回true;而==是比較兩字符串的地址是否相同,也就是是否是同一個字符串的引用。

例子5:

String是不可變的 : 這一說又要說很多,大家只要知道String的實例一旦生成就不會再改變了,比如說: String str=”aa”+”bb”+” “+”cc”; 就是有4個字符串常量,首先”aa”和”bb”生成了”aabb”存在內存中,后”aabb”又和” “ 生成 ”aabb “存在內存中,最后又和生成了”aabb cc”,並把這個字符串的地址賦給了str,就是因為String的“不可變”產生了很多臨時變量,這也就是為什么建議用StringBuffer的原因了。

三、StringBuffer和StringBuiler

我們對String、StringBuffer、StringBuiler先有一個簡單的認識。String是不可變字符串,StringBuffer和StringBuilder是長度可變的字符串,區別是前者是線程安全的,后者是線程不安全的,同樣后者的效率也會更高。

StringBuffer 上的主要操作是 append 和 insert 方法,可重載這些方法,以接受任意類型的數據。每個方法都能有效地將給定的數據轉換成字符串,然后將該字符串的字符追加或插入到字符串緩沖區中。append 方法始終將這些字符添加到緩沖區的末端;而 insert 方法則在指定的點添加字符。

例如,如果 z 引用一個當前內容為 "start" 的字符串緩沖區對象,則此方法調用 z.append("le") 會使字符串緩沖區包含 "startle",而 z.insert(4, "le") 將更改字符串緩沖區,使之包含 "starlet"。

通常,如果 sb 引用 StringBuilder 的一個實例,則 sb.append(x) 和 sb.insert(sb.length(), x) 具有相同的效果。

還有delete刪除方法 deleteCharAt(int index) delete(int start ,int end)

鏈接:url


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM