更新時間:2022-08-11 11:14:32 來源:動力節點 瀏覽1349次
比較常用的Java字符截取方法有哪些?動力節點小編為大家舉例說明。
1.length() 字符串的長度
示例:
char chars[]={'a','b'.'c'};
字符串 s=新字符串(字符);
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 的字符。接收到的字符數組由目標指定,目標中開始復制的子字符串的下標值為targetStart。
示例:
String s="this is a demo of the getChars method.";
字符 buf[]=新字符[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() 方法比較字符串對象中的字符,== 運算符比較兩個對象是否引用同一個實例。
示例:
字符串 s1="Hello";
字符串 s2=新字符串(s1);
s1.eauals(s2);//真
s1==s2;//假
10. compareTo() 和 compareToIgnoreCase() 比較字符串
11. indexOf() 和 lastIndexOf()
indexOf() 查找字符或子字符串的第一次出現。
lastIndexOf() 查找字符或子字符串最后一次出現的位置。
12. 子串()
它有兩種形式,第一種是:String substring(int startIndex)
第二個是:String substring(int startIndex,int endIndex)
13. concat()連接兩個字符串
14. replace()替換
它有兩種形式。第一種形式使用一個字符來替換調用字符串中出現的所有字符。
字符串替換(字符原始,字符替換)
例如: String s="Hello".replace('l','w');
第二種形式是將一個字符序列替換為另一個字符序列,形式如下:
字符串替換(CharSequence 原始,CharSequence 替換)
15. trim() 去掉開始和結束的空格
16. valueOf()轉換為字符串
17. toLowerCase() 轉換為小寫
18. toUpperCase() 轉換為大寫
19. StringBuffer 構造函數
StringBuffer 定義了三個構造函數:
字符串緩沖區()
字符串緩沖區(整數大小)
字符串緩沖區(字符串字符串)
StringBuffer(CharSequence 字符)
(1)長度()和容量()
一個StringBuffer的當前長度可以通過length()方法得到,整個可分配空間可以通過capacity()方法得到。
(2)ensureCapacity() 設置緩沖區的大小
無效確保容量(整數容量)
(3)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);
字符串 s=sb.append("a=").append(a).append("!").toString();
(7)insert() 插入字符串
StringBuffer 插入(int index,String str)
StringBuffer insert(int index,char ch)
StringBuffer 插入(int 索引,對象 obj)
index 指定字符串插入到 StringBuffer 對象的位置的索引。
(8)reverse() 反轉StringBuffer對象中的字符
字符串緩沖區反向()
(9)delete()和deleteCharAt()刪除字符
StringBuffer 刪除(int startIndex,int endIndex)
StringBuffer deleteCharAt(int loc)
(10)replace()替換
StringBuffer 替換(int startIndex,int endIndex,String str)
(11)substring()截取子串
字符串子字符串(int startIndex)
字符串子字符串(int startIndex,int endIndex)
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習