java查找字符串将找到的字符串索引位置存储到集合中

package com.hmkcode;

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

public class SearchStr {
	
	/**
	 * 查询字符串searchValue在字符串str中的位置索引(最多查询3位长度字符)
	 * @param str 一组字符串
	 * @param searchValue 要查找的字符串
	 * @return List<Integer> 存储查找的字符串索引
	 */
	public static List<Integer> searchStrIndex(String str,String searchValue){
		//定义存储查找的字符串索引集合
		List<Integer> searchIndexList = new ArrayList<Integer>();
		
		for(int i=0;i<str.length();i++){
			if(searchValue.length()==1){
				String ch1 = String.valueOf(str.charAt(i));
				if(ch1.equals(searchValue)){
					searchIndexList.add(i);
				}
			}else if(searchValue.length()==2){
				String ch1 = String.valueOf(str.charAt(i));
				String ch2;
				if(i<str.length()-1){
					ch2 = String.valueOf(str.charAt(i+1));
					String value = ch1+ch2;
					if(value.equals(searchValue)){
						searchIndexList.add(i);
					}
				}
			}else if(searchValue.length()==3){
				String ch1 = String.valueOf(str.charAt(i));
				String ch2;
				String ch3;
				if(i<str.length()-1){
					ch2 = String.valueOf(str.charAt(i+1));
					if(i<str.length()-2){
						ch3 = String.valueOf(str.charAt(i+2));
						String value = ch1+ch2+ch3;
						System.out.println(value);
						if(value.equals(searchValue)){
							searchIndexList.add(i);
						}
					}
				}
			}
		}
		return searchIndexList;
	}
	
	
	public static void main(String[] args) {
		List<Integer> searchIndexList = searchStrIndex("chabdeab89da+=()hkabd","abd");
		for(Integer index : searchIndexList){
			System.out.println("index:"+index.intValue());
		}
	}

}

你可能感兴趣的:(search)