2013-04-25 144 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"); 
}