Java:在字符串中获取匹配位置的方法?

Java: method to get position of a match in a String?

提问人:hhh 提问时间:4/11/2010 更新时间:9/26/2023 访问量:508383

问:

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

int position = getPosition(match, text); // should be 10, is there such a method?
Java 字符串 匹配

评论


答:

20赞 Michael Mrozek 4/11/2010 #1
text.indexOf(match);

请参阅 String javadoc

281赞 polygenelubricants 4/11/2010 #2

执行此操作的方法系列包括:

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


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"

评论

2赞 hhh 4/11/2010
哈哈,刚刚在while-loop中实现了一个赋值,然后你在for-loop +1中发布了一个赋值
4赞 Stephen C 4/11/2010
@polygenelubricants - 您的“查找所有匹配项”示例很聪明。但是,如果进行代码审查,你会得到一个关于代码可维护性的讲座。
3赞 polygenelubricants 4/11/2010
你会怎么写?老实说,我是在问,因为我以前没有专业的代码审查经验。
1赞 May Rest in Peace 2/6/2018
在查找所有匹配项时,我们可以编写 i += word.length(),而不是 i++。它应该稍微快一点。
0赞 Strauteka 2/3/2020
如果匹配一个字符,第一个循环将无法找到所有位置。你不需要 +1 in for 循环第二个语句,因为第三个语句会计算 i++ try for String text = “0011100”;匹配单词字符“1”,它将打印 2,4 而不是 2,3,4
2赞 hhh 4/11/2010 #3

你可以通过在 while-loop 内部分配来获得文件中的所有匹配项,很酷:

$ 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);
    }
}

评论

2赞 polygenelubricants 4/11/2010
你抵消的方式有效,但以一种相当迂回的方式。正如您在此处所示,它报告了第一个 。如果您始终使用从 0 开始的索引,则会更加一致。i+1helloi == 1
1赞 hhh 4/11/2010
...会偷走你的东西:P谢谢。
1赞 Noorus Khan 2/10/2014 #4
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);
  }
}

评论

1赞 Paul Hicks 2/10/2014
您能解释一下为什么这样做以及内循环的守卫发生了什么吗?解释可能对新手读者有用。
1赞 Noorus Khan 9/15/2014
int indexOf(String str, int fromIndex):从指定索引开始,返回此字符串中首次出现指定子字符串的索引。如果未发生,则返回 -1。在这里,while 的内部循环将能够获取 token 的所有占用(此处由名为“key”的变量指定)。
2赞 Sayed 3/3/2014 #5
int match_position=text.indexOf(match);

评论

1赞 Fabio 3/3/2014
请解释一下你做了什么
1赞 Sayed 3/25/2014
@Fabio getPosition(match, text){ int match_position=text.indexOf(match); 返回 match_position;}
13赞 Suragch 6/17/2015 #6

查找单个索引

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

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

查找多个索引

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

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);
}
0赞 JPeraita 6/22/2015 #7

如果您要扫描搜索字符串的“n”个匹配项,我建议使用正则表达式。 它们具有陡峭的学习曲线,但在进行复杂搜索时,它们将为您节省数小时。

评论

2赞 Brad Koch 10/15/2015
建议:包括一个从正则表达式获取位置的示例。只是“尝试使用正则表达式”是一个相当基本的评论,并不能回答OP的问题。
1赞 Nitika Goswami 7/8/2015 #8

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

   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;

                 }   
                }                 
              }  
           }  
         }
       }

评论

2赞 himawan_r 7/8/2015
在你的代码中加入一些解释/注释会让人们更容易理解你的代码,尤其是它的长代码:)
1赞 shravan 9/1/2015 #9
//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);

    }
}

评论

3赞 Peter Brittain 9/1/2015
虽然此代码可以回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高答案的长期价值。
50赞 Aldwane Viegan 11/7/2015 #10

这使用正则表达式工作。

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 中找到“爱”

通例:

  • 正则表达式从左到右搜索,一旦使用匹配字符,就无法重复使用。

评论

30赞 Gaurav Pangam 1/17/2018
这很棒,但是对于这句话,我得到的输出是“我有一个男朋友”:-)
0赞 Sarthak Ghosh 1/4/2018 #11

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

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);
    }


    }

}
1赞 Shukhrat Aliyev 4/14/2018 #12
    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);
0赞 yacine 5/29/2020 #13
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;
}

评论

0赞 Jaimil Patel 5/29/2020
希望它能解决问题,但请添加对您的代码的解释,以便用户完全理解他/她真正想要的。
0赞 LOGOUT 9/17/2022 #14
     class Main{
     public static int string(String str, String str1){
     for (int i = 0; i <= str.length() - str1.length(); i++){ 
        int j;
        for (j = 0; j < str1.length(); j++) {
            if (str1.charAt(j) != str.charAt(i + j)) {
                break;
            }
            }
           if (j == str1.length()) {
           return i;
           }}
           return -1;
             }
    public static void main(String[] args)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the string");
    String str=sc.nextLine();
    System.out.println("Enter the Substring");
    String str1=sc.nextLine();
    System.out.println("The position of the Substring is "+string(str, str1));
    }
    }

评论

1赞 Community 9/21/2022
正如目前所写的那样,你的答案尚不清楚。请编辑以添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以在帮助中心找到有关如何写出好答案的更多信息。
1赞 yash pal 9/21/2023 #15

我创建了一个非常容易理解的函数,用于查找单词在字符串中的位置,检查一下:-

public static void indexOfWordByYash() {
    String str = "01yash898989yashyashyashgggggg";
    String find = "yash";
    int sizeOfFind = find.length();
    System.out.println("length of string ="+str.length());
    System.out.println("size of find ="+sizeOfFind);
        
    //In here we are checking if find_word available from index 0, becouse 
    //in loop we are not checking from 0 index.
    int index = str.indexOf("yash", 0);
    for(int loop=0; loop < str.length(); loop++) {
            
        //Only if index greater then 0 will print the index.
        if(index >= 0) {
            System.out.println("Index of yash ="+index);
            index = str.indexOf("yash", index+sizeOfFind);
        }
            
        //Break the loop if no any more find_word in string.
        if(index == -1) {
            System.out.println("index ="+index);
            break;
        }
    }
}