美文网首页
String 字符串常用操作

String 字符串常用操作

作者: 大灰狼zz | 来源:发表于2018-10-27 10:55 被阅读0次

    indexof()方法

    Java中字符串中子串的查找共有四种方法,如下:
    1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。 
    2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
    3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。 
    4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
    示例:
        String string = "aaa456ac";  
      
        //查找指定字符是在字符串中的下标。在则返回所在字符串下标;不在则返回-1.  
        System.out.println(string.indexOf("b"));//indexOf(String str);返回结果:-1,"b"不存在  
      
        // 从第四个字符位置开始往后继续查找,包含当前位置  
        System.out.println(string.indexOf("a",3));//indexOf(String str, int fromIndex);返回结果:6  
      
        //(与之前的差别:上面的参数是 String 类型,下面的参数是 int 类型)参考数据:a-97,b-98,c-99  
      
        // 从头开始查找是否存在指定的字符  
        System.out.println(string.indexOf(99));//indexOf(int ch);返回结果:7  
        System.out.println(string.indexOf('c'));//indexOf(int ch);返回结果:7  
      
        //从fromIndex查找ch,这个是字符型变量,不是字符串。字符a对应的数字就是97。  
        System.out.println(string.indexOf(97,3));//indexOf(int ch, int fromIndex);返回结果:6  
        System.out.println(string.indexOf('a',3));//indexOf(int ch, int fromIndex);返回结果:6  
    

    substring() 方法
    substring() 方法返回字符串的子字符串

    语法:
    public String substring(int beginIndex)
    或
    public String substring(int beginIndex, int endIndex)
    参数
    beginIndex -- 起始索引(包括)。
    endIndex -- 结束索引(不包括)。
    示例:
            String Str = new String("www.runoob.com");
     
            System.out.println(Str.substring(4) );//返回值 :runoob.com
     
            System.out.println(Str.substring(4, 10) );//返回值 :runoob
    

    replace() 方法
    定义和用法
    replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

    replace(String str1,String str2) 的用法很简单: str2代替str1即可
    

    String.split()方法
    其实这个方法一般这样用:

    String[] arr = "11,22,33,44".split(",");
    

    从而方便的得到一个字符串数组:arr={"11", "22", "33", "44"};

    字符串拼接
    Android中几种字符串拼接的效率比较

    相关文章

      网友评论

          本文标题:String 字符串常用操作

          本文链接:https://www.haomeiwen.com/subject/gjztgftx.html