Java字串處理

來源:互聯網
上載者:User

標籤:

一、概述

Java是以String類型的對象來實現字串。String是一個類,當建立一個String對象後,所建立的字串是不能改變的。在需要使用可修改的字串時,Java提供兩個選擇—StringBuffer和StringBuilder。註:聲明為String引用的變數在任何時候都可以改變,以指向一些其他的String對象。

二、String建構函式

String s1="hello"與String s2=new String("hello")的區別:

String類在記憶體中管理一個字串常量池(常量池的一部分),池中所有相同的字串常量被合并,只佔用一個空間。

String s1=”hello”,先看池中有沒有hello,沒有就建立一個hello字串對象。即採用此方法建立0或者1個對象。

String s2=new String(“hello”),這裡先在池中建立一個hello對象,同s1,然後new String()時,將hello對象複製到堆heap中,s2指向堆中的hello。採用此種方法時建立1或2個對象(當池中有hello時,建立一個對象)。

記憶體配置圖如下:

三、String類的方法函數

String類有很多方法,這裡只介紹幾種常見的函數:

1、字串的長度:

int length();

2、字串轉換

每個類都會實現toString方法,因為它是由Obect定義的,對於大多數的自建立的類來說,通常要重寫toString()並提供自己的字串運算式。

eg:

 1 class Box  2 { 3     int x; 4     int y; 5     Box(int x,int y) 6     { 7         this.x=x; 8         this.y=y; 9     }10     public String toString()11     {12         return "test_x"+"-----"+x+"\n"+"test_y"+"-----"+y;13     }14 }15 public class Tset16 {17     public static void main(String[] args)18     {19             Box b=new Box(1,3);20             System.out.println(b);21     }22 23 }

顯示結果為:

疑問:看了一下println的源碼,不知道此處輸出結果為何是如此?

 1 private void write(String s) { 2         try { 3             synchronized (this) { 4                 ensureOpen(); 5                 textOut.write(s); 6                 textOut.flushBuffer(); 7                 charOut.flushBuffer(); 8                 if (autoFlush && (s.indexOf(‘\n‘) >= 0)) 9                     out.flush();10             }11         }12         catch (InterruptedIOException x) {13             Thread.currentThread().interrupt();14         }15         catch (IOException x) {16             trouble = true;17         }18     }

3、字元抽取

charAt():  返回指定索引處的 char 值。getChars():一次抽取多個字元。getBytes():將字元儲存在位元組數組裡。

4、字串比較

equals()和==:equals()方法是比較String對象中的字元,“==”運算子是比較兩個對象是否引用同一執行個體。

eg:

 1 public class Test 2 { 3     public static void main(String[] args) 4     { 5         String s1=new String("hello");//建立2個對象,一個pool和一個堆裡面  6         String s2="hello";//建立1個對象,s2指向pool裡面的"hello"對象  7         String s3="hello";//建立0個對象,指向s2指向pool裡面的那個對象  8         String s4=s2;//建立0個對象,指向s2,s3指向pool裡面的那個對象  9         String s5=new String("hello");//建立1個對象在堆裡面,注意,與s1沒關係 10 11         System.out.println(s2=="hello");//true 12         System.out.println(s2==s3);//true,因為指向的都是pool裡面的那個"hello" 13         System.out.println(s2==s4);//true,同上,那麼s3和s4...:) 14         System.out.println(s1==s5);//false,很明顯,false 15         System.out.println(s1==s2);//false,指向的對象不一樣16         System.out.println(s1=="hello");//false17         System.out.println("---------------"); 18         s1=s2; 19         System.out.println(s1=="hello");//true20     }21 }

執行結果:

boolean startsWith(String prefix):判斷給定的String是否以特定的字串開始。boolean startsWith(String prefix,int toffset):判斷此字元從指定索引開始的字串是否以指定的首碼開始。endsWith():判斷給定的String是否是以特定的字串結束。compareTo():用於比較字串大小,並考慮大小寫字母。compareIgnoreCase():比較字串大小並忽略大小寫字母。

5、尋找字串

isdexOf():尋找字元或子串第一次出現的位置lastIndexOf():尋找字元或者子串最後出現的位置

6、更改字串

因為String對象是不能改變的,當需要更改一個字串時,就必須將他複製到一個StringBuffered中,後者使用下列方法,在更改後會構造一個新的字串副本。

substring(int startIndex):返回從startIndex開始到調用字串結束的子串的一個副本substring(int startIndex,int endIndex),指定起點和終點,返回這中間的字串,不包括終點。concat():串連兩個字串,與“+”運算子相同。replace(char originial,char replacement):用一個字元在調用字串中所有出現另一個字元的地方進行替換。replace(CharSequence originial,CharSequence replacement):用一個字串序列替換另一個字串序列。trim():返回調用字串對象的一個副本,但是所有起始和結尾的空白符都被刪除了(字元中間的空白符未被刪除)。

7、改變字串中字元的大小寫

toLowerCase():將所有字元改為小寫toUpperCase():將所有字元改為大寫

四:StringBuffer類

StringBuffer是String的一個對等類,提供了字串的許多功能,可增長、可改寫。

這裡只介紹幾個StringBuffer類的方法函數:

1、append():將任何資料類型的字串表示串連到調用的StringBuffer對象的末尾。

當定String對象使用“+”運算子時,經常要調用append方法。

StringBuffer s=new StringBuffer("hello");    System.out.print(s.append(" world"));

2、inser(int index,String str):將一個字串插入到另一個字串中。

3、reverse():顛倒StringBuffer對象中的字元

4、delete(int startIndex,int endIndex),delete(int loc):調用對象中刪除一串字元。

五、StringBuilder類

除了一個重要的區別之外,與StringBuffer等同,這個區別是他不是同步的,意味著他不是安全執行緒的,其優勢是更快的效能,在使用多線程時必須使用StringBuffer。

Java字串處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.