148
String match = "hello";
String text = "0123456789hello0123456789";

int position = getPosition(match, text); // should be 10, is there such a method?
4

13 回答 13

276

执行此操作的方法系列是:

返回此字符串中第一次(或最后一次)出现指定子字符串的索引[从指定索引开始向前(或向后)搜索]。


String text = "0123hello9012hello8901hello7890";
String word = "hello";

System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"

// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
    System.out.println(i);
} // prints "4", "13", "22"

// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
    System.out.println(i);
} // prints "22", "13", "4"
于 2010-04-11T02:21:34.767 回答
48

这使用正则表达式。

String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);

while (match.find()) {
     System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}

输出 :

在索引 2 - 5 处找到“爱”

一般规则 :

  • 正则表达式从左到右搜索,一旦匹配字符被使用过,就不能重复使用。
于 2015-11-07T14:00:49.357 回答
20
text.indexOf(match);

请参阅字符串 javadoc

于 2010-04-11T01:46:01.250 回答
12

查找单个索引

正如其他人所说,用于text.indexOf(match)查找单个匹配项。

String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10

查找多个索引

由于@StephenC 对代码可维护性的评论以及我自己难以理解@polygenelubricants 的答案,我想找到另一种方法来获取文本字符串中匹配项的所有索引。以下代码(从this answer修改)这样做:

String text = "0123hello9012hello8901hello7890";
String match = "hello";

int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) {  // indexOf returns -1 if no match found
    System.out.println(index);
    index = text.indexOf(match, index + matchLength);
}
于 2015-06-17T00:28:44.327 回答
2

您可以通过在while循环中简单地分配来获取文件中的所有匹配项,很酷:

$ javac MatchTest.java 
$ java MatchTest 
1
16
31
46
$ cat MatchTest.java 
import java.util.*;
import java.io.*;

public class MatchTest {
    public static void main(String[] args){
        String match = "hello";
        String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
        int i =0;
        while((i=(text.indexOf(match,i)+1))>0)
            System.out.println(i);
    }
}
于 2010-04-11T02:21:47.667 回答
2
int match_position=text.indexOf(match);
于 2014-03-03T10:24:41.817 回答
1
import java.util.StringTokenizer;

public class Occourence {

  public static void main(String[] args) {
    String key=null,str ="my name noorus my name noorus";        
    int i=0,tot=0;

    StringTokenizer st=new StringTokenizer(str," ");
    while(st.hasMoreTokens())
    {   
        tot=tot+1;
        key = st.nextToken();
        while((i=(str.indexOf(key,i)+1))>0)
        {
            System.out.println("position of "+key+" "+"is "+(i-1));
        }
    }

    System.out.println("total words present in string "+tot);
  }
}
于 2014-02-09T20:34:59.563 回答
1

我有一些大代码,但工作得很好......

   class strDemo
   { 
       public static void main(String args[])
       {
       String s1=new String("The Ghost of The Arabean Sea");
           String s2=new String ("The");
           String s6=new String ("ehT");
           StringBuffer s3;
           StringBuffer s4=new StringBuffer(s1);
           StringBuffer s5=new StringBuffer(s2);
           char c1[]=new char[30];
           char c2[]=new char[5];
           char c3[]=new char[5];
           s1.getChars(0,28,c1,0);
           s2.getChars(0,3,c2,0);
           s6.getChars(0,3,c3,0); s3=s4.reverse();      
           int pf=0,pl=0;
           char c5[]=new char[30];
           s3.getChars(0,28,c5,0);
           for(int i=0;i<(s1.length()-s2.length());i++)
           {
               int j=0;
               if(pf<=1)
               {
                  while (c1[i+j]==c2[j] && j<=s2.length())
                  {           
                    j++;
                    System.out.println(s2.length()+" "+j);
                    if(j>=s2.length())
                    {
                       System.out.println("first match of(The) :->"+i);

                     }
                     pf=pf+1;         
                  }   
             }                
       }       
         for(int i=0;i<(s3.length()-s6.length()+1);i++)
        {
            int j=0;
            if(pl<=1)
            {
             while (c5[i+j]==c3[j] && j<=s6.length())
             {
                 j++;
                 System.out.println(s6.length()+" "+j);
                 if(j>=s6.length())
                 {
                         System.out.println((s3.length()-i-3));
                         pl=pl+1;

                 }   
                }                 
              }  
           }  
         }
       }
于 2015-07-08T07:58:39.113 回答
1
//finding a particular word any where inthe string and printing its index and occurence  
class IndOc
{
    public static void main(String[] args) 
    {
        String s="this is hyderabad city and this is";
        System.out.println("the given string is ");
        System.out.println("----------"+s);
        char ch[]=s.toCharArray();
        System.out.println(" ----word is found at ");
        int j=0,noc=0;
        for(int i=0;i<ch.length;i++)
        {
            j=i;

            if(ch[i]=='i' && ch[j+1]=='s')
            {
                System.out.println(" index "+i);
            noc++;  
            }

        }
        System.out.println("----- no of occurences are "+noc);

    }
}
于 2015-09-01T07:18:56.553 回答
1
    String match = "hello";
    String text = "0123456789hello0123456789hello";

    int j = 0;
    String indxOfmatch = "";

    for (int i = -1; i < text.length()+1; i++) {
        j =  text.indexOf("hello", i);
        if (i>=j && j > -1) {
            indxOfmatch += text.indexOf("hello", i)+" ";
        }
    }
    System.out.println(indxOfmatch);
于 2018-04-13T16:32:09.567 回答
0

如果您要扫描搜索字符串的“n”个匹配项,我建议您使用正则表达式。他们有一个陡峭的学习曲线,但在复杂的搜索方面,他们会为你节省几个小时。

于 2015-06-22T14:26:55.127 回答
0

对于多次出现和在字符串中找到的字符??是或否

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SubStringtest {

    public static void main(String[] args)throws Exception {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.println("enter the string");
    String str=br.readLine();
    System.out.println("enter the character which you want");
    CharSequence ch=br.readLine();   
    boolean bool=str.contains(ch);
    System.out.println("the character found is " +bool);
    int position=str.indexOf(ch.toString());

    while(position>=0){
        System.out.println("the index no of character is " +position); 
        position=str.indexOf(ch.toString(),position+1);
    }


    }

}
于 2018-01-04T06:30:41.957 回答
0
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
   {
    int iii1=0;
    int iii2=0;
    int iii3=0;
    while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
    // iii2 is the number of the occurences
    if(iii2>0) {
        positions_ = new int[iii2];
        while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
            positions_[iii3] = iii1-1;
            iii3 = iii3 + 1;
            System.out.println("position=" + positions_[iii3 - 1]);
        }
    }
    return iii2;
}
于 2020-05-29T08:29:29.617 回答