2013-04-25 158 views
0

我正在嘗試從一個句子中的單詞中搜索幾個特定字符串。最終這個句子將被用戶輸入,但我現在已經硬編碼了,以便於測試。如果程序找到字符串,它應該返回「Yes」和「No」,如果沒有。問題是,我一直都很滿意。如何爲特定字符串搜索字符串數組

public class main { 
public static void main(String[]args) 
{ 

    String Sentence = "This is a sentence"; 
    String[] CensorList = 
     {"big","head"}; 

    String[] words = Sentence.split(" "); 
    System.out.println(words.length); 
    boolean match = false; 

    for(int i = 0; i < words.length; i++) 
    { 
     for (int j = 0; j < CensorList.length; j++) 
     { 
      if(words[i].equals(CensorList[j])) 
      { 
       match = true; 
     }else{ 
      match = false; 
     } 
    } 

    } 
    if (match = true){ 
     System.out.println("Yes");} 
    else{ 
     System.out.println("No"); 
} 

}}

我會很感激的任何幫助,這一個,在此先感謝。

+0

沒有檢查你的代碼,但你肯定想刪除 ';'後if().. – 2013-04-25 13:20:59

回答

0

包含的功能可能是答案:

str1.toLowerCase().contains(str2.toLowerCase()) 
2
如果

的你的第二個()有錯誤的大括號。

試試這個:

for (int j = 0; j < CensorList.length; j++) 
{ 
    if(words[i].equals (CensorList[j])) { 
     match = true; 
     System.out.println("Yes"); 
    } else { 
     System.out.println("No"); 
    } 
    match = false; 
} 

你的第二個嘗試:

if (match = true) 

不與真正的比較匹配,它設置匹配標誌爲真,結果總是如此。

比較標誌在你的,如果:

if (match == true) // or simply if (match) 
{ .... 
+0

謝謝這工作得很好,我已經更新我的代碼打印出是/否的消息只有一次。但是它只能重新印刷。我不認爲你可以用這個錯誤指向正確的方向。麻煩抱歉。 – user1048104 2013-04-25 13:46:21

+0

檢查我的答案,它可能會影響你;) – duffy356 2013-04-25 14:37:53

1

試試:

for(int i = 0; i < words.length; i++) 
{ 
    for (int j = 0; j < CensorList.length; j++) 
    { 
     if(words[i].equals (CensorList[j])) 
      match = true; 
    } 
      if (match) { 
       System.out.println("Yes"); } 
      else { 
       System.out.println("No"); } 
      match = false; 
} 
1

我覺得你有一些錯別字在這裏。

for (int j = 0; j < CensorList.length; j++) 
    { 
      if(words[i].equals (CensorList[j])); 
    } 

這樣做基本上什麼都不會做,因爲如果表達式評估爲true,那麼if沒有任何關係。然後在循環後設置匹配爲真,那麼這將是真正的始終,它總是會打印出「是」

0

嘗試使用

public class main { 
public static void main(String[]args) 
{ 

    String Sentence = "This is a sentence"; 
    String[] CensorList = 
     {"This","No"}; 

    String[] words = Sentence.split(" "); 
    System.out.println(words.length); 
    boolean match = false; 

    for(int i = 0; i < words.length; i++) 
    { 
     for (int j = 0; j < CensorList.length; j++) 
     { 
      if(words[i].compareTo(CensorList[j])==0) 
      { 
       System.out.println("Yes"); 
      } 
      else{System.out.println("No");} 

     } 
    } 

} 
1

您可以使用一個簡單的正則表達式基礎的解決方案爲這個

private static boolean test(String value) { 
    String[] CensorList = { "This", "No" }; 

    for (String string : CensorList) { 
     Pattern pattern = Pattern.compile("\\b" + string + "\\b", Pattern.CASE_INSENSITIVE); 
     if (pattern.matcher(value).find()) { 
      return true; 
     } 
    } 
    return false; 
} 

然後

String string = "This is a sentence"; 
if(test(string)){ 
    System.out.println("Censored"); 
}