1. 程式人生 > >String型別的常用方法

String型別的常用方法

1.public String concat(String str),將指定字串聯到此字串的結尾。
str - 串聯到此 String 結尾,並返回一個新的String。

String s ="我愛你,";
String s1=s.concat("I Love You!");
System.out.println(s1);//我愛你,I Love You!

2.public String intern(),返回字串物件的規範化表示形式。一個初始時為空的字串池,它由類 String 私有地維護。
對於任何兩個字串 s 和 t,當且僅當 s.equals(t) 為 true 時,s.intern() == t.intern() 才為 true。

String s ="我愛你,";
s.intern();

3.public String replace(char oldChar,char newChar),用newChar替換在此字串中的oldChar,生成新的String。

String s="我愛使用奧拉夫。";
String s1=s.replace('我','你');
System.out.println(s1);//你愛使用奧拉夫。

4.public String replace(CharSequence target,CharSequence replacement),使用指定的字面值替換序列替換此字串匹配字面值目標序列的每個子字串。該替換從此字串的開始一直到結束。

String s="我愛使用奧拉夫。";
String s1=s.replace('奧拉夫','德萊文');
System.out.println(s1);//我愛使用德萊文。

5.**public String substring(int beginIndex)**從指定beginIndex索引開始,到此字串結束,返回一個新的字串,是此字串的子字串。

String s="我愛使用奧拉夫。";
String s1=s.substring(4);
System.out.println(s1);//奧拉夫。

6.**public String substring(int beginIndex,int endIndex)**返回一個新字串,它是此字串的一個子字串。該子字串從指定的 beginIndex 處開始,一直到索引 endIndex - 1 處的字元。
引數:beginIndex-開始處的索引(包括)。endIndex-結束處的索引(不包括)。

String s="我愛使用奧拉夫。";
String s1=s.substring(2,4);
System.out.println(s1)//我愛奧拉夫。

7.**public String toLowerCase()**使用預設語言環境的規則將此 String 中的所有字元都轉換為小寫。

String s="ASDasdSDsd";
String s1=s.toLowerCase();
System.out.println(s1);//asdasdsdsd

8.**public String toUpperCase()**使用預設語言環境的規則將此 String 中的所有字元都轉換為大寫。

String s="ASDasdSDsd";
String s1=s.toUpperCase();
System.out.println(s1);//ASDASDSDSD

9.**public String trim()**返回字串的副本,忽略前導空白和尾部空白。

String s="     asd       ";
String s1=s.trim;
System.out.println(s1);//asd

10.**public static String valueOf(char[] data,int offset, int count)**返回 char 陣列引數的特定子陣列的字串表示形式。返回一個字串,它表示在字元陣列引數的子陣列中包含的字元序列。
引數:data-字元陣列。offset-String 值的初始偏移量。count-String 值的長度。
例如:有一個字元陣列char[] arr={‘i’,‘l’,‘o’,‘v’,‘e’,‘y’,‘o’,‘u’};我想讓它中有些連續的字元以字串的形式打印出來;比如說love。

        char[] arr={'i','l','o','v','e','y','o','u'};
        String s="隨便一個字串";
        String s1 = s.valueOf(arr, 1, 4);
        System.out.println(s1);//love

11.**public static String copyValueOf(char[] data,int offset,int count)**返回指定陣列中表示該字元序列的字串。 返回一個字串,它包含字元陣列的指定子陣列的字元。
引數:data - 字元陣列。offset - 子陣列的初始偏移量。count - 子陣列的長度。

        char[] arr={'i','l','o','v','e','y','o','u'};
        String s="隨便一個字串";
        String s1 = s.copyValueOf(arr, 1, 4);
        System.out.println(s1);//love