我想从一段文字中提取所有匹配的字符串位置,
例如:万里长城万里长
我要提取所有“万里”的位置

解决方案 »

  1.   

    Sting里面有相关的方法自己去查,如果没有就考虑正则表达式
      

  2.   


    int location li[];
    int lo=0;
    for(int i=0; i<str.length(); i++){
    if("万" == str.charAt(i))
      if("里" == str.charAt(i+1)){
    li[lo++] = i;//这样li[]数组里即保存了满足条件的位置,是保存的“万”的下标位置。
    }
    }你试试。
      

  3.   

    这个问题很好。
    现在我只能算出有几个。
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test01 { private static final String str = "万里长城万里长"; 
    public static void main(String args[]) {
    split() ;
    } // 第一种方法split
    public static void split() {
    int count = 0;
    Pattern pattern = Pattern.compile("万里");
    Matcher m = pattern.matcher(str);
    while (m.find()) {
    count++;
    }
    System.out.println("个数有:" + count);
    }
    }
      

  4.   


            String str="万里长城万里长";
    String matched="万里";
    int bgnIndex=0;
    int site=0; //记录匹配字串所在的位置

    while((site=str.indexOf(matched,bgnIndex))!=-1){
    bgnIndex=site+matched.length();
    System.out.println(site);
    }如果字符串很长,建议使用正则,考虑效率问题。
      

  5.   

    呵呵,这里的新人蛮多的,建议参考我楼上的回答。有api就使用api。但是考虑效率用正则。
      

  6.   

    好解决了。
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test01 { private static final String str = "万里长城万里长"; 
    public static void main(String args[]) {
    split() ;
    } // 第一种方法split
    public static void split() {
    int count = 0;
    Pattern pattern = Pattern.compile("万里");
    Matcher m = pattern.matcher(str);
    while (m.find()) {
     System.out.println(m.group()); 
         System.out.print("start:"+m.start()); 
         System.out.println(" end:"+m.end());  }
    }
    }
      

  7.   

    正则表达式,或是用filterchain