2017-11-8課堂作業查找字符串位置

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/liuxiaowei_java96/article/details/78477812

查找字符串位置

查找字符串”hello,world!hello,china!hello,jiangsu!”中“hello”出現的所有位置。

package com.ntqn;

import java.util.ArrayList;
import java.util.List;

public class Demo6 {
    public static void main(String[] args) {
        //字符串
        String str = "hello,world!hello,china!hello,jiangsu!";
        //需要查找位置的字符串
        String str1 = "hello";
        //調用靜態方法,用於list接收索引集合
        List<Integer> list = getIndexsOfStr(str, str1);

        //循環遍歷出list中的索引值
        for (Integer i : list) {
            System.out.println(i);
        }       
    }

    public static List<Integer> getIndexsOfStr(String src, String c) {
        //創建rs集合,用於存儲c出現的位置索引
        List<Integer> rs = new ArrayList<Integer>();

        if (null != src) {
            //初始化index
            Integer index = 0;
            //循環實現c的位置索引
            while (index < src.length()) {
                //返回指定子字符串在此字符串中第一次出現處的索引,從指定的索引開始。
                index = src.indexOf(c,index);
                //判斷是否存在,如果不存在會返回-1。
                if (index < 0) {
                    //不存在,就結束循環
                    break;
                } else {
                    //存在,就將索引添加到list集合中,指定的索引加上子串的長度繼續循環
                    rs.add(index);
                    index = index + c.length(); 
                }       
            }
        }
        //返回rs
        return rs;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章