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

猜你喜欢

转载自blog.csdn.net/B_Belief/article/details/83419208
今日推荐