जावा: एक स्ट्रिंग में मैच की स्थिति प्राप्त करने की विधि?


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

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

जवाबों:


259

ऐसा करने वाले तरीकों के परिवार हैं:

निर्दिष्ट पदार्थ के पहले ( या अंतिम ) घटना के इस स्ट्रिंग के भीतर सूचकांक लौटाता है [ निर्दिष्ट सूचकांक में शुरू होने वाले ( या पिछड़े ) खोजते हुए ]।


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
लोलज़, बस लूप-इन के अंदर एक असाइनमेंट का एहसास हुआ, तो आप लूप के लिए एक असाइनमेंट पोस्ट करते हैं +1
hhh

4
@ पॉलीऑक्सीजेलूबेन्डर - आपके "सभी घटनाएँ पाते हैं" उदाहरण चतुर हैं। लेकिन अगर कोड की समीक्षा की जा रही है, तो आपको कोड में स्थिरता के बारे में व्याख्यान मिलेगा।
स्टीफन C

3
आप इसे कैसे लिखेंगे? मैं ईमानदारी से पूछ रहा हूं, क्योंकि मेरे पास पहले पेशेवर कोड समीक्षा का अनुभव नहीं था।
पॉलीजेन लुब्रिकेंट्स

1
सभी घटनाओं को खोजने में, i ++ के बजाय, हम i + = word.length () लिख सकते हैं। यह थोड़ा तेज होना चाहिए।
शांति में आराम कर सकते हैं

पहला लूप सभी पदों को खोजने में विफल होगा यदि एक चार का मिलान किया जाए। लूप सेकंड स्टेटमेंट के लिए आपको +1 की आवश्यकता नहीं है, क्योंकि तीसरा स्टेटमेंट i ++ स्ट्रिंग पाठ = "0011100" के लिए प्रयास करता है; मिलान शब्द "1" यह २,४ नहीं २,३,४ को
छपेगा

40

यह रेगेक्स का उपयोग करके काम करता है।

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 में 'प्यार' मिला

सामान्य नियम :

  • रेगेक्स खोज दाएं से बाएं, और एक बार मैच वर्णों का उपयोग करने के बाद, इसका पुन: उपयोग नहीं किया जा सकता है।

19
यह कमाल का काम करता है, लेकिन इस वाक्य के लिए मुझे यह कहते हुए आउटपुट मिला कि "मेरा एक बॉयफ्रेंड है" :-)
गौरव पंगम


8

एकल सूचकांक ढूँढना

जैसा कि अन्य लोगों ने कहा है, text.indexOf(match)एकल मैच खोजने के लिए उपयोग करें।

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

कई सूचकांक खोज रहा है

कोड स्टेफिबिलिटी के बारे में @ स्टीफन की टिप्पणी और @polygenel स्नेहक के उत्तर को समझने में मेरी अपनी कठिनाई के कारण , मैं एक टेक्स्ट स्ट्रिंग में मैच के सभी इंडेक्स पाने के लिए एक और तरीका खोजना चाहता था। निम्न कोड (जो इस उत्तर से संशोधित है ) ऐसा करता है:

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


2

आप एक फाइल में सभी मेल प्राप्त कर सकते हैं बस अंदर जबकि-लूप, कूल असाइन करके:

$ 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
जिस तरह से आप ऑफसेट iद्वारा +1काम करता है, लेकिन एक नहीं बल्कि राउंडअबाउट रास्ते में। यहां जो दिखाया है के रूप में, यह पहली रिपोर्ट helloमें i == 1। यदि आप हमेशा 0-आधारित अनुक्रमण का उपयोग करते हैं तो यह अधिक सुसंगत है।
पॉलीजेन लुब्रिकेंट

1
... आपकी बात चुरा लेगा: P धन्यवाद।
hhh

2
int match_position=text.indexOf(match);

1
कृपया बताएं कि आपने क्या किया
Fabio

1
@ फैबियो गेटपोस (मैच, टेक्स्ट) {इंट मैच_पोजिशन = टेक्स्ट.इंडेक्सऑफ (मैच); वापसी मिलान_पोजिशन;}
सईद

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

1
क्या आप बता सकते हैं कि यह क्यों काम करता है और आंतरिक लूप के संरक्षण में क्या हो रहा है? एक स्पष्टीकरण एक नौसिखिया पाठक के लिए उपयोगी हो सकता है।
पॉल हिक्स

1
int indexOf (स्ट्रिंग str, int fromIndex): निर्दिष्ट विकल्प पर शुरू होने वाले निर्दिष्ट सबस्ट्रिंग की पहली स्ट्रिंग के भीतर इस सूचकांक को वापस लौटाता है। यदि ऐसा नहीं होता है, तो -1 लौटा दिया जाता है। यहां का आंतरिक लूप, टोकन के सभी स्रोत प्राप्त करने में सक्षम होगा (यहां 'कुंजी' के रूप में नामित चर द्वारा निर्दिष्ट किया गया है)।
खान

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;

                 }   
                }                 
              }  
           }  
         }
       }

2
अपने कोड में कुछ स्पष्टीकरण / टिप्पणी रखें, जिससे लोगों को आपके कोड को समझने में आसानी होगी, विशेष रूप से यह लंबा कोड है :)
himawan_r

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

    }
}

3
हालांकि यह कोड प्रश्न का उत्तर दे सकता है, लेकिन यह समस्या का हल कैसे और / या इसके बारे में अतिरिक्त संदर्भ प्रदान करता है, इससे उत्तर के दीर्घकालिक मूल्य में सुधार होगा।
पीटर ब्रिटैन

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

0

यदि आप खोज स्ट्रिंग के 'एन' मैचों के लिए स्कैन करने जा रहे हैं, तो मैं नियमित अभिव्यक्ति का उपयोग करने की सलाह दूंगा । उनके पास एक कठिन सीखने की अवस्था है, लेकिन जब वे जटिल खोजों की बात करते हैं तो वे आपको घंटों बचाएंगे।


2
सुझाव: एक नियमित अभिव्यक्ति से स्थिति प्राप्त करने का एक उदाहरण शामिल करें। बस "नियमित अभिव्यक्ति का उपयोग करने का प्रयास करें" एक बल्कि बुनियादी टिप्पणी है और ओपी के सवाल का जवाब नहीं देता है।
ब्रैड कोच

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


    }

}

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

आशा है कि यह समस्या को हल कर देगा, लेकिन कृपया इसके साथ अपने कोड की व्याख्या जोड़ें ताकि उपयोगकर्ता को सही समझ मिल जाएगी जिसे वह वास्तव में चाहता है।
जयमिल पटेल
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.