`
wb284551926
  • 浏览: 539195 次
文章分类
社区版块
存档分类
最新评论

String字符串查找指定字符位置(原创)

 
阅读更多

public class FindIndex {
    public static int findIndex(String str,String splitstr,int index){
        String[] strarr = str.split(splitstr);
        int len = 0;
        if(index>0&&index<strarr.length){
            for(int i=0;i<index;i++){
                len += strarr[i].length()+1;
            }
        }
        return len-1;
    }
    public static void main(String[] args) {
        String str="asdfjlkj.sdfasfd.afdsafasfd.gg.2.23.23.432432...2234432.445";
        String splitstr = "\\."; // .这个比较特殊需要转义
        int index = findIndex(str,splitstr,4);
        if(index!=-1){
            System.out.println(splitstr+"'s index is "+index);
            System.out.println("Index "+index+" is "+str.charAt(index));
        }else{
            System.out.println("String index out of range");
        }
    }
}

 

输出结果:

\.'s index is 30
Index 30 is .

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics