JAVA字元串的方法
1、length() 字元串的長度
例:char chars[]={'a','b'.'c'};
String s=new String(chars);
int len=s.length();
2、charAt() 截取一個字元
例:char ch;
ch="abc".charAt(1); 傳回'b'
3、getChars() 截取多個字元
void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)
sourceStart指定了子串開始字元的下标,sourceEnd指定了子串結束後的下一個字元的下标。是以,子串包含從sourceStart到sourceEnd-1的字元。接收字元的數組由target指定,target中開始複制子串的下标值是targetStart。
例:String s="this is a demo of the getChars method.";
char buf[]=new char[20];
s.getChars(10,14,buf,0);
4、getBytes()
替代getChars()的一種方法是将字元存儲在位元組數組中,該方法即getBytes()。
5、toCharArray()
6、equals()和equalsIgnoreCase() 比較兩個字元串
7、regionMatches() 用于比較一個字元串中特定區域與另一特定區域,它有一個重載的形式允許在比較中忽略大小寫。
boolean regionMatches(int startIndex,String str2,int str2StartIndex,int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex,String str2,int str2StartIndex,int numChars)
8、startsWith()和endsWith()
startsWith()方法決定是否以特定字元串開始,endWith()方法決定是否以特定字元串結束
9、equals()和==
equals()方法比較字元串對象中的字元,==運算符比較兩個對象是否引用同一執行個體。
例:String s1="Hello";
String s2=new String(s1);
s1.eauals(s2); //true
s1==s2;//false
10、compareTo()和compareToIgnoreCase() 比較字元串
11、indexOf()和lastIndexOf()
indexOf() 查找字元或者子串第一次出現的地方。
lastIndexOf() 查找字元或者子串是後一次出現的地方。
12、substring()
它有兩種形式,第一種是:String substring(int startIndex)
第二種是:String substring(int startIndex,int endIndex)
13、concat() 連接配接兩個字元串
14 、replace() 替換
它有兩種形式,第一種形式用一個字元在調用字元串中所有出現某個字元的地方進行替換,形式如下:
String replace(char original,char replacement)
例如:String s="Hello".replace('l','w');
第二種形式是用一個字元序列替換另一個字元序列,形式如下:
String replace(CharSequence original,CharSequence replacement)
15、trim() 去掉起始和結尾的空格
16、valueOf() 轉換為字元串
17、toLowerCase() 轉換為小寫
18、toUpperCase() 轉換為大寫
19、StringBuffer構造函數
StringBuffer定義了三個構造函數:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
(1)、length()和capacity()
一個StringBuffer目前長度可通過length()方法得到,而整個可配置設定空間通過capacity()方法得到。
(2)、ensureCapacity() 設定緩沖區的大小
void ensureCapacity(int capacity)
(3)、setLength() 設定緩沖區的長度
void setLength(int len)
(4)、charAt()和setCharAt()
char charAt(int where)
void setCharAt(int where,char ch)
(5)、getChars()
void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)
(6)、append() 可把任何類型資料的字元串表示連接配接到調用的StringBuffer對象的末尾。
例:int a=42;
StringBuffer sb=new StringBuffer(40);
String s=sb.append("a=").append(a).append("!").toString();
(7)、insert() 插入字元串
StringBuffer insert(int index,String str)
StringBuffer insert(int index,char ch)
StringBuffer insert(int index,Object obj)
index指定将字元串插入到StringBuffer對象中的位置的下标。
(8)、reverse() 颠倒StringBuffer對象中的字元
StringBuffer reverse()
(9)、delete()和deleteCharAt() 删除字元
StringBuffer delete(int startIndex,int endIndex)
StringBuffer deleteCharAt(int loc)
(10)、replace() 替換
StringBuffer replace(int startIndex,int endIndex,String str)
(11)、substring() 截取子串
String substring(int startIndex)
String substring(int startIndex,int endIndex)