2016-11-19 78 views
-1
public class CharMatch { 
    private void matchString(String s1, String s2) { 
     int count = 0; 
     int len1 = s1.length(); 
     int len2 = s2.length(); 
     for (int i = 0; i < len2; i++) { 
      for (int j = 0; j < len1; j++) { 
       if (s2.charAt(i) == s1.charAt(j)) { 
        count++; 
       } 
       if (count == len2) { 
        System.out.print("True");} 
       } 
      } 
    }  

    public static void main(String args[]) throws IOException { 
     CharMatch cm = new CharMatch(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("Enter First String"); 
     String a = br.readLine(); 
     System.out.println("Enter Second String"); 
     String b= br.readLine(); 
     cm.matchString(a,b); 
    } 
} 

我在寫這個代碼輸入的兩個字符串,例如輸入:s1="Hello world" s2:"woeh"則輸出應該如果s2比賽中的所有字符是真實的在s1中至少一次。這是我寫的代碼,但我沒有達到理想的輸出。檢查的第二個字符串中的所有字符是否與存在於第一個字符串中的字符匹配至少一次

回答

1

這是我寫的代碼,但可根據需要,我不是完美的輸出得到。

您的代碼有幾個問題。

  • 作爲@MacRyze提到,在中"Hello world"字符匹配"woeh"的問題是,你需要爲小寫你的字符串,如果你想'h',以配合的情況下,不區分大小寫'H'方式。
  • 另一個大問題是,你將在第一個字符串中計數字符'o'兩次,我認爲你不想這樣做。一旦找到第一個字符匹配,您應該在count++;之後休息一下。此外,您應該在與count++相同的塊中測試if (count == len2) {,然後您應該從該方法返回,如果它爲真。您也可以在方法結束時執行此操作。

最終,如果您使用了一個調試器並逐步通過該示例,則應該能夠找到此錯誤。這是一個很好的tutorial for eclipse

我精的代碼位和使用的String.indexOf(...)方法和到達:

private void matchString(String s1, String s2) { 
    int matchCount = 0; 
    s1 = s1.toLowerCase(); 
    s2 = s2.toLowerCase(); 
    // go through all characters in the match string 
    for (char ch : s2.toCharArray()) { 
     // look for the character in the first string 
     if (s1.indexOf(ch) >= 0) { 
      matchCount++; 
     } 
    } 
    if (matchCount == s2.length()) { 
     System.out.print("True"); 
    } 
} 
-1

使用java string contains()方法搜索此字符串中的字符序列。如果在此字符串中發現char值序列,則返回true,否則返回false。

void matchString(String s1,String s2) 
{ 
    if(s2.contains(s1)) 
     System.out.print("True"); 
    else 
     System.out.print("False"); 

} 
+0

更多信息請參考這裏http://stackoverflow.com/questions/767759/occurrences-of-substring- in-a-string –

+0

海報希望以任意順序查找字符,而不是按順序查找完整字符串。 – Gray

+0

這就是我從上面的代碼中所理解的。 –

0

我想這是非常重要的,如果字符的情況下很重要。如果不是我想這一點的代碼應該做的工作:

 s1 = s1.toLowerCase(); 
     s2 = s2.toLowerCase(); 
     boolean flag = true; 
     for(char element : s2.toCharArray()){ 
      if(!s1.contains(Character.toString(element))){ 
       flag = false; 
      } 
     } 
     System.out.println(flag); 

在另一方面,如果字符大小寫事項只是刪除s1 = s1.toLowerCase();s2 = s2.toLowerCase();。 祝你好運!

+0

創建一個字符的字符串,以便您可以執行一個包含代碼是非常昂貴的。使用String.indexof(ch)代替字符。 – Gray

+0

是的,你是對的灰色,你的版本似乎比我的好。感謝評論,我還有很多要學習! –

相關問題