2016-03-15 64 views
-6

分配給我的任務是從字符串中查找給定模式的所有可能組合。像給定的字符串是01001001001001. 我必須找到多少次01001出現在給定的字符串?所以我要求的正確答案是給定字符串中存在的4種可能的01001組合。我怎樣才能使代碼在Java或C#中成爲可能?我已經嘗試過,但只有兩個字符串匹配。在Java或C中匹配字符串#

package regularexpressions; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import java.util.regex.*; 
import java.util.Scanner; 


public class RegularExpressions { 


public static void main(String[] args) { 

     Scanner sc = new Scanner(System.in); 

     System.out.println("Enter the main string: "); 

     String main = sc.nextLine(); 

     System.out.println("Enter the pattern string: "); 

     String patern = sc.nextLine(); 

     Pattern p = Pattern.compile(patern); 
     // get a matcher object 

     Matcher m = p.matcher(main); 

    System.out.println("The input String is="+input); 

     System.out.println("The Pattren to be recgnoized is="+pattren); 

     while(m.find()) { 

      count++; 
      System.out.println("Match number " 
           + count); 
      System.out.println("start(): " 
           + m.start()); 
      System.out.println("end(): " 
           + m.end());     

} 

} 
+2

你至少應該嘗試做你的功課,並配備了一個代碼示例當/如果它不工作 – Boo

+0

同意。至少顯示出一些證據表明這是一種趨勢 –

+0

通過IndexOf(「01001」,start)搜索,直到找不到更多變體。 –

回答

0

這就是你要複製並粘貼到Java的公共類和嘗試

String givenString = "01001001001001"; 

    String pattern = "01001"; 
    int j = 0,count = 0; 
    int matchChar = 0; 
    int temp = 0; 

    for(int i = 0; i < (givenString.length() - pattern.length() + 1); i++) 
    { 

     if(givenString.charAt(i) == pattern.charAt(j)) 
     { 
      temp = i; 
      while(givenString.charAt(temp) == pattern.charAt(j) && j < pattern.length() - 1) 
       { 
        matchChar++; 
        temp++; 
        j++; 
       } 
      j = 0; 
     } 
     j = 0; 
     if(matchChar == 4) 
       count += 1; 
     matchChar = 0; 
    } 
    System.out.println(count);