有字符串abcd efg abc,我要查找abc出现的位置,要是匹配到完整一个abc单词才返回``如果匹配到一个串的一部分则不返回``完整的一个abc是根据两边的空格而定`是匹配一个指定的单词才返回``请问怎样写?我再说明白点`单词的长度不定,有可能不是3个`

解决方案 »

  1.   

    public class MatchStr {
    public static void main(String args[]){
    String src = "abcd efg abc";
    String match = "abc";

    int off;
    if((off = src.indexOf(" "+match+" ")) !=-1){
    System.out.println(off);
    }
    else if((off = src.indexOf(" "+match)) !=-1){
    System.out.println(off);
    }

    else{
    System.out.println("no matcher!");
    }
    }
    }
      

  2.   

    import java.util.StringTokenizer;
    public class MatchStr {
    public static void main(String args[]){
    String src = "abc dlaj abc abcd abc abc";
    String match = "abc";
    StringTokenizer s = new StringTokenizer(src);
    String word;
    boolean isMatch = false;
    int off = 0;
    while(s.hasMoreTokens()){
    word = s.nextToken();
    if(word.equals(match)) {
    System.out.println(off);
    isMatch = true;
    }
    off += word.length()+1;
    }
    if(isMatch == false) {
    System.out.println("no match!");
    }
    }
    }
      

  3.   

    刚才那个处理的字符串,如果是空格大于1隔就不好控制单词所在的位置了,刚才那个程序默认是只有1隔的,所以是word.length()+1;现在这个不存在这个矛盾了
    public class MatchStr {
    public static void main(String args[]){
    String src = "abc  dlaj abc abcd  abc abc";
    String match = "abc";
    int i = 0;
    boolean isMatch = false;
    if(src.startsWith(match+" ")==true){
    System.out.println(i);
    }
    while(i<src.length()){
    if(src.startsWith(" "+match+" ",i)==true){
    System.out.println(i+1);
    i = i+ 4;
    isMatch = true;
    continue;

    }
    else if(src.startsWith(" "+match,i)==true&&i == (src.length()-4)){
    System.out.println(i+1);
    isMatch = true;
    break;
    }
    i++;
    }



    if(isMatch== false){
    System.out.println("no matcher!");
    }
    }
    }