【问题标题】:Java: method to get position of a match in a String?Java:获取字符串中匹配位置的方法?
【发布时间】:2011-02-06 15:05:28
【问题描述】:
String match = "hello";
String text = "0123456789hello0123456789";

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

【问题讨论】:

    标签: java string match


    【解决方案1】:
    text.indexOf(match);
    

    String javadoc

    【讨论】:

      【解决方案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"
      

      【讨论】:

      • lolz,刚刚在while循环中实现了一个赋值,然后你在for循环+1中发布了一个赋值
      • @polygenelubricants - 你的“查找所有出现”的例子很聪明。但如果是代码审查,你会得到一个关于代码可维护性的讲座。
      • 你会怎么写?我说实话,因为我之前没有专业的代码审查经验。
      • 在查找所有出现的地方,我们可以写 i += word.length(),而不是 i++。应该会快一些。
      • 如果匹配一个字符,第一个循环将无法找到所有位置。您不需要在 for 循环第二个语句中 +1,因为第三个语句确实计数 i++ try for String text = "0011100";匹配单词 char "1" 它将打印 2,4 而不是 2,3,4
      【解决方案3】:

      你可以通过在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);
          }
      }
      

      【讨论】:

      • +1 抵消i 的方式有效,但是以一种相当迂回的方式。正如您在此处显示的,它在i == 1 报告第一个hello。如果您始终使用从 0 开始的索引,则会更加一致。
      • ... 会偷你的东西 :P 谢谢。
      【解决方案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);
        }
      }
      

      【讨论】:

      • 您能解释一下为什么会这样以及内循环的保护中发生了什么吗?解释可能对新手读者有用。
      • int indexOf(String str, int fromIndex):返回此字符串中第一次出现指定子字符串的索引,从指定索引开始。如果没有发生,则返回 -1。这里while的内部循环将能够获取token的所有出现(这里由名为'key'的变量指定)。
      【解决方案5】:
      int match_position=text.indexOf(match);
      

      【讨论】:

      • 请解释一下你做了什么
      • @Fabio getPosition(match, text){ int match_position=text.indexOf(match);返回匹配位置;}
      【解决方案6】:

      查找单个索引

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

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

      查找多个索引

      由于@StephenC's comment 关于代码可维护性以及我自己理解@polygenelubricants' answer 的困难,我想找到另一种方法来获取文本字符串中匹配项的所有索引。下面的代码(从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);
      }
      

      【讨论】:

        【解决方案7】:

        如果您要扫描搜索字符串的“n”个匹配项,我建议使用 regular expressions。 它们的学习曲线陡峭,但在复杂搜索方面可以为您节省数小时。

        【讨论】:

        • 建议:包括一个从正则表达式中获取位置的示例。只是“尝试使用正则表达式”是一个相当基本的评论,并没有回答 OP 的问题。
        【解决方案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;
        
                         }   
                        }                 
                      }  
                   }  
                 }
               }
        

        【讨论】:

        • 在你的代码中加入一些解释/注释会让人们更容易理解你的代码,尤其是长代码:)
        【解决方案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);
        
            }
        }
        

        【讨论】:

        • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
        【解决方案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 找到“爱”

        一般规则:

        • 正则表达式从左到右搜索,一旦匹配字符被使用过,就不能重复使用了。

        【讨论】:

        • 这很棒,但是对于这句话,我得到的输出是“我有男朋友”:-)
        【解决方案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);
            }
        
        
            }
        
        }
        

        【讨论】:

          【解决方案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);
          

          【讨论】:

            【解决方案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;
            }
            

            【讨论】:

            • 希望它能解决问题,但请添加对代码的解释,以便用户完全理解他/她真正想要的。
            猜你喜欢
            • 2019-05-31
            • 2013-06-12
            • 2023-03-18
            • 2012-10-30
            • 2019-07-20
            • 2011-11-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多