代码改变世界

Java String学习部分心得,持续更新

2019-02-28 22:31  进击的菜鸟123  阅读(431)  评论(0)    收藏  举报

String部分函数功能及用法

1)获取字符串长度 str.length()   用法:String str = "Hello World";int size = str.length();

2)获取字符位置(字符串获取) str.indexOf()   用法:String str = "Hello World";int size = str.index("s");  ps:第一个s的位置

                                       str.lastindexOf(). 用法:String str = "Hello World";int size = str.lastindex("s");  ps:最后一个s位置   是不是能获取中间位置的s位置呢,这个研究下补充

3)获取指定索引位置的字符str.charAt(int index)  用法:  String str = "Hello Word";char mychar = str.charAt(3);

4)截取字符串 str.substring(int beginIndex) 用法:String str = "Hello Word";String substr = str.substring(3);   ps:从3开始到结束

                      str.substring(int beginIndex,int endIndex)  用法:String str = "Hello World"; String substr = str.substring(3,7);    ps:截取3到6之间的字符

5)去掉字符串前后空格  str.trim()    用法:String str = "  Hello  World  ";String trimstr = str.trim();

6)字符串替换 str.replace(char oldChar,char newChar)   用法:String str = "abcdeef";String newstr = str.replace('a','A');

7)判断字符串的开始 str.startsWith()  用法:String str = "123456";boolean b = str.startsWith("12");

8)判断字符串的结束 str.endsWith()  用法:String str = "123456";boolean b = str.endsWith("56");

9)判断字符串是否相等 str.equals(String otherstr)  用法:String str = new String("abc");String otherstr = new String("ABC"); boolean b = str.equals(otherstr);   ps:这个指的是完全相等 

                   str.equalsIngoreCase(String otherstr)  用法:String str = new String("abc");String otherstr = new String("ABC"); boolean b = str.equalsIngoreCase(otherstr);   ps:这个指的是忽略大小写                

10)比较两个字符串 str.compareTo(otherstr)  用法:String str = new String("a");String otherstr = new String("b");int num = str.compare(otherstr);  ps:num值为整数,说明str比较大;num值为负数,说明str比较小;num值为0,说明两个字符串相等

11)将字符串中大写字母转换为小写 str.toLowerCase()   用法:String str = new String("abcDEF"); String newstr = str.toLowerCase();

12)将字符串中小写字母转换为大写 str.toUpperCase()   用法:String str = new String("abcDEF"); String newstr = str.toUpperCase();

13)将字符串进行分割 str.split(String sign)  用法:String str = new String("abc,bcd,cde,def"); String newstr[] = str.split(",");   ps:结果 abc  bcd  cde  def

           str.split(String sign,int limit)  用法  :String str = new String("abc,bcd,cde,def"); String newstr[] = str.split(",",2);  ps:结果 abc  bcd,cde,def