JavaString常用函數(shù)

字符與字符串

很多的語言之中都是利用了字符數(shù)組的概念來描述字符串的信息,這一點很多語言都用到了。

No 方法名稱 類型 描述
1 public String (char [] value) 構(gòu)造 將字符數(shù)組轉(zhuǎn)換為字符串
2 public String (char [] value,int offset,int count) 構(gòu)造 將部分字符數(shù)組轉(zhuǎn)換為字符串
3 public char charAt(int index) 普通 返回制定索引的字符串
4 public char[] toCharArray() 普通 將字符串以字符數(shù)組形式返回

范例:取出制定索引的字符

public class StringDemo{
    public static void main(String []args){
        String str = "hello";
        char c = str.charAt(0);
        System.out.println(c);
    }
}

范例:將字符串變成字符數(shù)組

public class StringDemo{
    public static void main(String []args){
        String str = "hello";
        char[] charArray = str.toCharArray();
    }
}

范例:將字符串轉(zhuǎn)大寫

public class StringDemo{
    public static void main(String []args){
        String str = "hello";
        char[] charArray = str.toCharArray();
        for(int i = 0;i < charArray.length; i ++){
            //小寫變?yōu)榇髮懚蟛ぃ恍枰獪p去32即可
            charArray[i] -= 32;
        }
        System.out.println(new String(charArray));
        System.out.println(new String(charArray,1,2));
    }
}

范例:給定一個字符串,要求判斷是否由數(shù)字組成

public class StringDemo{
    public static void main(String [] args){
        String str = "123321";
        if(isNumber(str)){
            System.out.println("字符串由數(shù)組組成");
        }else{
            System.out.println("字符串不是由數(shù)組組成");
        }
    }
    // 判斷字符串是否為數(shù)組組成,是返回true,否返回false
    public static boolean isNumber(String temp){        
        char [] data = temp.toCharArray();
        for(int x = 0; x <data.length;x++){
            if(data[x] > '9' || data[x] < '0'){
                return false;
            }
        }
        return true;
    }
}

字節(jié)與字符串

字節(jié)使用byte描述想帅,使用字節(jié)一般主要用于數(shù)據(jù)的傳輸或者是編碼的轉(zhuǎn)換的時候使用,而在String里面未玻,就提供了將字符串變?yōu)樽止?jié)數(shù)組的操作颅和,目的就是為了傳輸以及編碼轉(zhuǎn)換。

No 方法名稱 類型 描述
1 public String (byte[] bytes) 構(gòu)造 將全部的字節(jié)數(shù)組變?yōu)樽址?/td>
2 public Strint(byte[] bytes,int offset,int length) 構(gòu)造 將部分字節(jié)數(shù)組變?yōu)樽址?/td>
3 public byte[] getBytes() 普通 將字符串變?yōu)樽止?jié)數(shù)組
4 public byte[] getBytes(String chasetName) throws UnsupportedEncodingException 普通 進(jìn)行編碼轉(zhuǎn)換

范例:觀察字符串與字節(jié)數(shù)組的轉(zhuǎn)換

public class StringDemo{
    public static void main(String []args){
        String str = "HelloWorld";
        byte []data = str.getBytes();//將字符串變?yōu)樽止?jié)數(shù)組
        for(int i = 0 ; i < data.length ; i++){
             data[x] -= 32;//變?yōu)榇髮?        }
        System.out.println(new String(data));
        System.out.println(new String(data,5,5));
    }
}

因為現(xiàn)在操作的是因為字母茎辐,所以感覺與字符類似宪郊,

在以后講解IO操作的時候會牽連到這種字節(jié)數(shù)組的操作,會涉及到亂碼轉(zhuǎn)碼的問題

字符串的比較

如果要進(jìn)行字符串內(nèi)容相等的判斷使用equals()拖陆,但是在String類里面定義的比較判斷不止這一個弛槐。

No 方法名稱 類型 描述
1 public boolean equals(String object) 普通 進(jìn)行相等的判斷,它區(qū)分大小寫
2 public boolean equalsIgnoreCase(String temp) 普通 進(jìn)行相等的判斷依啰,不區(qū)分大小寫
3 public int compareTo(String anotherString) 普通 判斷兩個字符串的大泻醮(按照字符編碼比較),此方法的返回值有三種結(jié)果: = 0:表示要比較的兩個字符串內(nèi)容相等速警;:>0:表示大于的結(jié)果叹誉;<0:表示小于的結(jié)果
4
5
6

范例:觀察comparaTo(String temp)方法

public class StringDemo{
    public static void main(String []args){
        String stra = "hello";
        String strb = "HELLO";
        System.out.println(stra.comparaTo(strb));
        //32,結(jié)果是 stra > strb 
    }
}

現(xiàn)在只有String類的對象才具有大小的關(guān)系判斷闷旧。

字符串查找

從一個完整的字符串之中要判斷某一個子字符串是否存在长豁,這個功能可以使用如下的方法完成。

No MethodName Type Description
1 public boolean contains(String temp) 普通 判斷指定的內(nèi)容是否存在忙灼,如果存在返回true
2 public int indexOf(String str) 普通 由前向后查找指定字符串的位置匠襟,如果查找到了钝侠,那么就返回位置的(第一個字母)索引,如果找不到酸舍,那么返回 -1帅韧。
3 public int indexOf(String str, int fromIndex) 普通 由指定位置開始從前向后查找字符串的位置,找不到返回 -1啃勉;
4 public int lastIndexOf(String str) 普通 由后向前查找指定字符串的位置忽舟,找不到返回 -1;
5 public int lastIndexOf(String str, int fromIndex) 普通 從指定位置由后向前查找字符串的位置璧亮,找不到返回 -1萧诫;
6 public boolean startsWith(String prefix) 普通 判斷是否以指定的字符串開頭,如果是返回true枝嘶,否則返回false
7 public boolean startsWith(String prefix, int toffset) 普通 從指定為位置開始帘饶,判斷是否以指定字符串開頭
8 public boolean endsWith(String suffix) 普通 判斷是否以指定字符串結(jié)尾

范例:使用indexOf()等功能進(jìn)行查找

public class StringDemo{
    public static void main(String []args){
        String str = "HelloWorld";
        // 返回滿足條件的第一個單詞的索引
        System.out.println(str.indexOf("World"));
        // 返回的是第一個查找到的
        System.out.println(str.indexOf("l"));
        // 從第五個開始查找
        System.out.println(str.indexOf("l",5));
        // 從后往前找
        System.out.println(str.lastIndexOf("l"));
    }
}

從JDK1.5之后出現(xiàn)了contains()方法,這個方法可以直接返回boolean群扶,這樣省略了我們很多代碼及刻,我們也推薦使用這樣的方法來判斷是否包含該字符串。

字符串替換

指的就是使用心得字符串替換掉舊的字符串?dāng)?shù)據(jù)竞阐,支持的方法有如下缴饭。

No MethodName Type Description
1 public String replaceAll(String regex,String replacement) 普通 用新的內(nèi)容提替換掉全部舊的內(nèi)容
2 public String replaceFirst(String regex,String replacement) 普通 替換首個滿足條件的內(nèi)容

范例:觀察替換結(jié)果

public class StringDemo{
    public static void main(String []args){
        String str = "HelloWorld";
        System.out.println(str.replaceAll("l","_"));
        System.out.println(str.replaceFirst("l","_"));
    }
}

字符串截取

從一個完整的字符串之中可以截取部分的子字符串?dāng)?shù)據(jù),支持的方法如下

No MethodName Type Description
1 public String substring(int beginIndex) 普通 從指定的索引截取到結(jié)尾
2 public String substring(int beginIndex,int endIndex) 普通 截取部分子字符串的數(shù)據(jù)
public class StringDemo{
    public static void main(String [] args){
        String str = "HelloWorld";
        String resultA = str.substring(5);
        String resultB = str.substring(0,5);
        System.out.println(resultA);
        System.out.println(resultB);
    }
}

一定要記住骆莹,數(shù)據(jù)庫中的函數(shù)由于考慮到是非專業(yè)人員使用操作颗搂,所以有些代碼盡可能做了一些調(diào)整,但是程序是要求嚴(yán)謹(jǐn)性的幕垦,所以負(fù)數(shù)是不可能使用負(fù)數(shù)作為截取的開始點丢氢。

字符串拆分

將一個完整的字符串,按照指定的內(nèi)容先改,拆分為字符串?dāng)?shù)組(對象數(shù)組疚察,String對象),方法如下仇奶。

No MethodName Type Description
1 public String[] split(String regex) 普通 按照指定字符串拆分為字符串?dāng)?shù)組
2 public String[] split(String regex) 普通 按照指定字符串進(jìn)行部分拆分貌嫡,最后的一個數(shù)組的長度由limit決定的。

范例

public class StringDemo{
    public static void main(String [] args){
        String str = "HelloWorld";
        //根據(jù)空格拆分字符串?dāng)?shù)組
        String[] result = str.split(" ");
        for(int i = 0 ; i < result.length ; i++ ){
            System.out.println(result[x]);
        }
    }
}

如果在拆分的時候只是寫了一個空字符串(""该溯,不是null)岛抄,那么就會按照每一個字符拆分

范例:拆分IP地址

public class StringDemo{
    public static void main(String [] args){
        String str = "192.168.1.2";
        String[] result = str.split(".");
        for(int i = 0 ;i < result.length ; i++){
            System.out.println(result[i]);
        }
    }
}

然后一運行發(fā)現(xiàn),并沒有拆分開來狈茉,沒有輸出任何東西弦撩,原因:需要轉(zhuǎn)義,系統(tǒng)識別不了

public class StringDemo{
    public static void main(String [] args){
        String str = "192.168.1.2";
        String[] result = str.split("\\.");
        for(int i = 0 ;i < result.length ; i++){
            System.out.println(result[i]);
        }
    }
}

如果是一寫敏感字符(正則標(biāo)記)论皆,嚴(yán)格來說是拆分不了的,如果真的遇見了拆分不了的情況,那么使用 \\(就是轉(zhuǎn)義)点晴,進(jìn)行轉(zhuǎn)義后感凤,才可以拆分。

范例:進(jìn)行以下字符串

public class StringDemo{
    public static void main(String [] args){
        String str = "張三:18|李四:20|王五:24";
        String [] result = str.split("\\|");
        for(int i : 0 ; i < result.length ; i++){
            String temp[] = result[i].split(":");
            System.out.println("姓名:"+temp[0]+"粒督,年齡:"+temp[0]);
        }       
    }
}

以后的格式可以由你根據(jù)需要任意的組合陪竿。

其他方法

以上給出的方法是可以歸類的,但是在String里面也有一部分的方法是不能歸類的

No MethodName Type Description
1 public String concat(String str) 普通 字符串的鏈接屠橄,與“ + ”類似
2 public String toLowerCase() 普通 字符串轉(zhuǎn)小寫
3 public String toUpperCase() 普通 字符串轉(zhuǎn)大寫
4 public String trim() 普通 去掉字符串兩邊空格族跛,留下中間空格
5 public int length() 普通 取得字符串長度
6 public String intern() 普通 字符串入池
7 public boolean isEmpty() 普通 判斷是否是空字符串(空字符串不是null,而是""锐墙,長度0)
8
9

范例:字符串的連接

public class StringDemo{
    public static void main(String[] args){
        String stra = "hello";
        stra.concat("");
        String strb = "hello "+"world"; 
        String strc = "hello world"
        System.out.println(strb == strc);
    }
}

范例: 轉(zhuǎn)小寫與大寫

public class StringDemo{
    public static void main(String[] args){
        String stra = "hello*(*)"
        System.out.println(stra.toUpperCase());
        System.out.println(stra.toLowerCase());
    }
}

非字母字符不會被轉(zhuǎn)義

范例:去掉空格

public class StringDemo{
    public static void main(String[] args){
        String str = "   hello    ";
        System.out.println("【"+str+"】");
        System.out.println("【"+str.trim()+"】");
    }
}

一般在用戶進(jìn)行輸入的時候礁哄,有可能會帶有無用的空格內(nèi)容,那么接受到這些數(shù)據(jù)后溪北,就會消除掉所有的空格內(nèi)容

范例:取得字符串的長度

public class StringDemo{
    public static void main(String[] args){
        String str = "helloworld";
        System.out.println(str.length());
    }
}

在某些情況下桐绒,我們會要求用戶輸入的數(shù)據(jù)長度是有限的,可以利用此方法判斷數(shù)據(jù)長度之拨。

  • 數(shù)組對象.length
  • String對象.length()

范例:判斷是否為空字符串

public class StringDemo{
    public static void main(String[] args){
        String str = "helloworld";
        // false
        System.out.println(str.isEmpty);
        // true
        System.out.println("".isEmpty);
    }
}

如果覺得isEmpty()不方便茉继,可以使用 "".equals(str)

String類雖然提供了大量的支持的方法,但是卻少了一個很重要的方法蚀乔,而這樣的方法只能由我們自己實現(xiàn)烁竭。

public class StringDemo{
    public static void main(String [] args){
        String str = "helloWorld";
        System.out.println(initcap(str));
    }
    // 首字母大寫
    public static String initcap(String temp){
        return temp.substring(0,1).toUpperCase()+temp.substring(1);
    }
}

雖然Java的類庫里面沒有此類功能,但是很多第三方的組件包會提供吉挣。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末派撕,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子听想,更是在濱河造成了極大的恐慌腥刹,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件汉买,死亡現(xiàn)場離奇詭異衔峰,居然都是意外死亡,警方通過查閱死者的電腦和手機蛙粘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進(jìn)店門垫卤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人出牧,你說我怎么就攤上這事穴肘。” “怎么了舔痕?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵评抚,是天一觀的道長豹缀。 經(jīng)常有香客問我,道長慨代,這世上最難降的妖魔是什么邢笙? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮侍匙,結(jié)果婚禮上氮惯,老公的妹妹穿的比我還像新娘。我一直安慰自己想暗,他們只是感情好妇汗,可當(dāng)我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著说莫,像睡著了一般杨箭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上唬滑,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天告唆,我揣著相機與錄音,去河邊找鬼晶密。 笑死擒悬,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的稻艰。 我是一名探鬼主播懂牧,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼尊勿!你這毒婦竟也來了僧凤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤元扔,失蹤者是張志新(化名)和其女友劉穎躯保,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體澎语,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡途事,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了擅羞。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片尸变。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖减俏,靈堂內(nèi)的尸體忽然破棺而出召烂,到底是詐尸還是另有隱情,我是刑警寧澤娃承,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布奏夫,位于F島的核電站怕篷,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏桶蛔。R本人自食惡果不足惜匙头,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望仔雷。 院中可真熱鬧,春花似錦舔示、人聲如沸碟婆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽竖共。三九已至,卻和暖如春俺祠,著一層夾襖步出監(jiān)牢的瞬間公给,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工蜘渣, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留淌铐,地道東北人。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓蔫缸,卻偏偏與公主長得像腿准,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子拾碌,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容