Java 字符串操作的总结1(转载)
一.Java字符串類基本概念
在JAVA語言中,字符串數據實際上由String類所實現的。Java字符串類分為兩類:一類是在程序中不會被改變長度的不變字符串;二類是在程序中會被改變長度的可變字符串。Java環境為了存儲和維護這兩類字符串提供了 String和StringBuffer兩個類。
?一、創建字符串
例: 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()方法。
sb.setCharAt(2, “b”);?// 結果aabaaa
轉載于:https://www.cnblogs.com/mei-sweety/p/4703070.html
總結
以上是生活随笔為你收集整理的Java 字符串操作的总结1(转载)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: button-xml 中android:
- 下一篇: 前端构建工具gulp入门教程