Java 字串操作的總結1(轉載)

來源:互聯網
上載者:User

標籤:

一.Java字串類基本概念

在JAVA語言中,字串資料實際上由String類所實現的。Java字串類分為兩類:一類是在程式中不會被改變長度的不變字串;二類是在程式中會被改變長度的可變字串。Java環境為了儲存和維護這兩類字串提供了 StringStringBuffer兩個類。
 一、建立字串
例: Stringstr=new("This is a String");

或者 Stringstr="This is a String";

 二、得到字串對象的有關資訊
1.通過調用length()方法得到String的長度.
例:

String str="Thisis a String";
int len =str.length();

2.StringBuffer類的capacity()方法與String類的 length()的方法類似,但是她測試是分配給StringBuffer的記憶體空間的大小,而不是當前被使用了的記憶體空間。
3.如果想確定字串中指定字元或子字串在給定字串的位置,可以用 indexOf()lastIndexOf()方法。

String str="Thisis a String";
Int index1 =str.indexOf("i");   //index=2
Intindex2=str.indexOf(‘i‘,index+1);   //index2=5
Intindex3=str.lastIndexOf("I");   //index3=15
Intindex4=str.indexOf("String");  //index4=10



三、String對象的比較和操作
1.String對象的比較
String類的equals()方法用來確定兩個字串是否相等。

String str="Thisis a String";
Boolean result=str.equals("This is another String");
//result=false


2.String對象的訪問
A、方法charAt()用以得到指定位置的字元。

String str="Thisis a String";
char chr=str.charAt(3);//chr="i"


B、方法getChars()用以得到字串的一部分字串

public voidgetChars(int srcBegin,intsrcEnd,char[]dst,intdstBegin)
String str="Thisis a String";
Char chr =new char[10];
Str.getChars(5,12,chr,0);  //chr="isa St"


C、subString()是提取字串的另一種方法,它可以指定從何處開始提取字串以及何處結束。
3.操作字串
A、replace()方法可以將字串中的一個字元替換為另一個字元。

String str="Thisis a String";
String str1=str.replace(‘T‘,‘t‘); //str1="thisis a String"


B、concat()方法可以把兩個字串合并為一個字串。

String str="Thisis a String";
String str1=str.concat("Test");//str1="Thisis a String Test"


C、toUpperCase()toLowerCase()方法分別實現字串大小寫轉換。

String str="THISIS A STRING";
String str1=str.toLowerCase(); //str1="thisis a string";


D、trim()方法可以將字串中開頭和結尾處的空格去掉.

String str="Thisis a String   ";
String str1=str.trim();   //str1="This is a String"


E、String類提供靜態方法valueOf(),它可以將任何類型的資料對象轉換為一個字串。如

System.out.println(String,ValueOf(math,PI));


四、修改可變字串
StringBuffer類為可變字串的修改提供了3種方法,在字串中間插入和改變某個位置所在的字元。
1.在字串後面追加:用append()方法將各種對象加入到字串中。
2.在字串中間插入:用insert()方法。例

StringBuffer str=new StringBuffer("Thisis a String");
Str.insert(9,"test");
System.out.println(str.toString());


這段代碼輸出為:Thisis a test String
3.改變某個位置所在的字元,用setCharAt()方法。

StringBuffer sb =new StringBuffer("aaaaaa");

sb.setCharAt(2, “b”); // 結果aabaaa

Java 字串操作的總結1(轉載)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.