Java基础之字符串String:
String
-----------------------------------------------------------------------------------------
一、String類適用于描述字符串事物。
??? 那么它就提供了多個方法對字符串進(jìn)行操作。
常見的操作有哪些?
"abcd"
1,獲取
?? 1.1 字符串中的包含的字符數(shù),也就是字符串的長度。
?????? int length() : 獲取長度。
?? 1.2 根據(jù)位置獲取位置上某個字符。
?????? char charAt(int index):
??
?? 1.3 根據(jù)字符獲取該字符在字符串中位置
?????? int indexOf(int ch) :返回的是ch在字符串中第一次出現(xiàn)的位置。
?????? int indexOf(int ch,int fromIndex) :從fromIndex指定位置開始,獲取ch在字符串中出現(xiàn)的位置
?????? int indexOf(String str) :返回的是str在字符串中第一次出現(xiàn)的位置
?????? int indexOf(String str,int fromIndex) :從fromIndex指定位置開始,獲取str在字符串中出現(xiàn)的位置
?????? int lastIndexOf(int ch) :
2,判斷
?? 2.1 字符串中是否包含某一個子串
?????? boolean contains(str);
??????
?????? 特殊之處:indexOf(str):可以索引str第一次出現(xiàn)的位置,如果返回-1,表示該str不在字符串中存在。
?????? 所以,也可以用于對指定判斷是否包含。
?????? if(str.indexOf("aa")>-1)
?????? 而且該訪法即可判斷,也可獲取出現(xiàn)的位置,如果單純的判斷使用 contains,如果即要判斷又要獲取位置使用 indexOf(str)
?? 2.2 字符串中是否有內(nèi)容
?????? boolean isEmpty(); 原理就是判斷長度是否為0.
??
?? 2.3 字符器是否是以指定內(nèi)容開頭
?????? boolean startWith(str);
??????
?? 2.4 字符串是否是以指定內(nèi)容結(jié)尾
?????? boolean endsWith(str);
?? 2.5 判斷字符串的內(nèi)容是否相同,復(fù)寫了Object類中的equals方法。
?????? boolean equals(str);
?? 2.6 判斷內(nèi)容是否相同,并且忽略大小寫。
?????? boolean equalsIgnoreCase();
3,轉(zhuǎn)換
?? 3.1 將字符數(shù)組轉(zhuǎn)換成字符串
?????? 構(gòu)造函數(shù):String(char[])
???????????????? String(char[] data,int offset,int count):將字符數(shù)組中的一部分轉(zhuǎn)成字符串。
?????? 靜態(tài)方法:static String copyValueOf(char[]);
???????????????? static String copyValueOf(char[] data,int offset,int count);
???????????????? static String valueOf(char[]);
?? 3.2 將字符串轉(zhuǎn)換成字符數(shù)組
?????? char[] toCharArray();
?? 3.3 將字節(jié)數(shù)組轉(zhuǎn)換成字符串
?????? String(byte[]);
?????? String(byte[] data,int offset,int count);將字節(jié)數(shù)組中的一部分轉(zhuǎn)成字符串。
?? 3.4 將字符串轉(zhuǎn)換成字節(jié)數(shù)組
?????? byte[] getBytes();
?? 3.5 將基本數(shù)據(jù)類型轉(zhuǎn)換成字符串
?????? static String valueOf(int);
?????? static String valueOf(double);
?????? 特殊:字符串和字節(jié)數(shù)組在轉(zhuǎn)換過程中,是可以指定編碼表的。
4,替換
?? String replace(oldchar,newchar);如果要替換的字符不存,返回的還是原串。
?? String replace(oldstring,newstring);
??
5,切割
?? String[] split(string regex);
6,子串,獲取字符串中的一部分
?? String substring(int beginIndex);
?? String substring(int beginIndex,int endIndex);
7,轉(zhuǎn)換,去除空格,比較。
?? 7.1 將字符串轉(zhuǎn)成大寫或者小寫
?????? String toUpperCase();
?????? String toLowerCase();
?? 7.2 將字符串兩端的多個空格去除
?????? String trim();
?? 7.3 對兩個字符串進(jìn)行自然順序的比較
?????? int compareTo(string);
?
轉(zhuǎn)載于:https://www.cnblogs.com/cxmsky/archive/2013/01/15/2862007.html
總結(jié)
以上是生活随笔為你收集整理的Java基础之字符串String:的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript高性能编程笔记(个人
- 下一篇: python 在列表中完成队列的删除和排