java 检查字符串是否具有特定单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13489419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:57:36  来源:igfitidea点击:

Check if string has a specific word

javastring

提问by user1778856

My String wordscontains a bunch of words separated by a \n(and ends in an \n). The code adds words to the string, only if the word isn't already there. These blocks of code are within a forloop, with wbeing the word to add.

MyString words包含一堆由 a 分隔的单词\n(并以 an 结尾\n)。代码将单词添加到字符串中,仅当单词不存在时。这些代码块在一个for循环中,w是要添加的单词。

I have

我有

loop: if (w.contains("" + letter)) //This is just to test the words I want to add
{
  for (String s : words.split("\n"))
    if (w.equals(s))
      break loop;
  words += w + "\n";
}

And

if (w.contains("" + letter))
{
  if (!words.contains("\n"+w+"\n") && words.indexOf(w+"\n") != 0)
    words += w + "\n";
}

But both seem messy in their own ways. Is there another way to go about this, or which method would perform more quickly.

但两者都以自己的方式看起来很混乱。有没有其他方法可以解决这个问题,或者哪种方法执行得更快。

回答by Rohit Jain

First of all, ifis not a loop. So there is no point in labelling it so as use a labelled break.

首先,if不是循环。所以没有必要标记它以便使用标记的中断。

Secondly, both of your code isn't really doing, what you said you want to do. Also, I don't understand why are you doing if (w.equals(s))this test. And what is wused for.

其次,你的两个代码都没有真正做,你说你想做的。另外,我不明白你为什么要做if (w.equals(s))这个测试。以及w用来做什么。

You said: - w being the word to add, but again you are saying that, you will add the words from your string after splitting it on "\n", if it is not already in your array. So, you are adding many words, not just one word. Please re-read your post, and edit it if necessary.

你说: - w being the word to add,但你又是这么说的"\n",如果你的array. 因此,您添加了许多单词,而不仅仅是一个单词。请重新阅读您的帖子,并在必要时进行编辑。



As per your current problem statement, I would approach it like this: -

根据您当前的问题陈述,我会这样处理:-

  • First split your lines on "\n"to get an array with individual words.
  • I would rather use StringBuilderor StringBufferif I want to modify my string on each iteration.
  • Now, on each iteration, check whether your StringBuilderalready contains that word. If it does not contains, then append it, else leave it.
  • At the end of your loop, print your StringBuilderinstance.
  • 首先拆分您的行"\n"以获取包含单个单词的数组。
  • 我宁愿使用StringBuilder或者StringBuffer如果我想在每次迭代时修改我的字符串。
  • 现在,在每次迭代中,检查您是否StringBuilder已经包含该word. 如果它不包含,则附加它,否则留下它。
  • 在循环结束时,打印您的StringBuilder实例。


Or, as you are saying, you can also use an ArrayListto store your words. Or if, you want uniquewords only, you should rather use a Setinstead. That would not require you to do the test. It handles the duplicates on its own: -

或者,正如您所说,您也可以使用 anArrayList来存储您的单词。或者,如果您unique只想要单词,则应该使用 aSet代替。那不需要你做测试。它自己处理重复项:-

List<String> wordList = new ArrayList<String>();

Set<String> set = new LinkedHashSet<String>();

for (String s : words.split("\n")) {

    if (s.contains("" + letter)) {

        if (!wordList.contains(s)) {
            wordList.add(s);   // Add to list. 
        }
        set.add(s);   // Add to set.
    }
}

And then print your ArrayListor Setby iterating over either of them.

然后通过迭代它们中的任何一个来打印您的ArrayListor Set

回答by Shivraj Yadav

// if u r trying to find a word/specific word in a string,this code will definitely help u..

// 如果你试图在字符串中找到一个词/特定词,这段代码肯定会帮助你..

public class findWordFromString {

公共类 findWordFromString {

public static void main(String[] A)
{
    String str = "Manhattan is a great company";
    String search = "great";
    boolean flag= false;

// here first split or break the string,based on the space present btween each word
    String[] arr = str.split(" "); 
      for(int i=0;i<arr.length;i++)
     {

        if(arr[i].**equals**(search)) // here,never use == instead of equals()  
        {
          flag = true;
            break;
        }
     }//for loop

        if(flag)
        {
           System.out.println(search+" is present");    
        }else
        {
            System.out.println(search+" is not present");
        }
}//method

}//class

}//班级

回答by Pawel Solarski

I would store the distinct words you are adding in List;

我会将您添加的不同单词存储在 List 中;

List<String> words = new ArrayList<String>();

void addWord(String word){
    if(!words.contains(word)){
        words.add(word);
    }
}

String listAsString(){
    StringBuilder buffer = new StringBuilder();
    for(String word: words){
        buffer.append(word);
        buffer.append("\n");
    }
    return buffer.toString();
}      

回答by vels4j

I would suggest to use a List

我建议使用列表

ArrayList<String> wordList = new ArrayList() ;
// to add
if (w.contains("" + letter) && wordList.contains(w) )
{
   wordList.add(w);
}
//at the end you can append \n
StringBuilder bdr = new StringBuilder() ;
for(String word : wordList)
{
     bdr.append(word).append("\n");
}
String words = bdr.toString();

回答by Sajid Hussain

Here is fast way to find the specific word in string. without splitting and looping it.

这是在字符串中查找特定单词的快速方法。没有分裂和循环它。

public static void main(String[] args) {
      String w = "This\nis\nTesting\nString\nthat\ncontains\nHelloWorld\n";
      String searchingWord = "HelloWorld";
      Pattern pattern= Pattern.compile("("+searchingWord+")");
      Matcher matcher = pattern.matcher(w);
      if(!matcher.find())
      {
         System.out.println("Word Not Found");
      }else
      {
         System.out.println("Word Found");
      }

}

回答by chris.tian

If you check whether new words are contained and the delimiter is \n then you will need regular expressions. Relying on contains alone would not add words with are sub-sequences of existing word.

如果您检查是否包含新单词并且分隔符是 \n,那么您将需要正则表达式。仅依靠 contains 不会添加带有现有单词的子序列的单词。

public class AddWords {

    public String addWord(final String newWord, final String allWords) {
        String result = allWords;
        Pattern p = Pattern.compile(".*\n" + newWord + "\n.*");
        Matcher m = p.matcher(allWords);
        if (!m.find()) {
            StringBuffer buf = new StringBuffer();
            buf.append(allWords);
            buf.append(newWord);
            buf.append("\n");
            result = buf.toString();
        }
        return result;
    }
}

To better understand the matter I have added a unit test for that scenario:

为了更好地理解这个问题,我为该场景添加了一个单元测试:

public class AddWordsTest {
    @Test
    public void addExistingWord() {
        String allWords = "\nfoo\nbar\n";
        String notNewWord = "foo";
        AddWords aw = new AddWords();
        String newAllWords = aw.addWord(notNewWord, allWords);
        Assert.assertEquals(allWords, newAllWords);
    }

    @Test
    //This would fail if you rely on contains!!!
    public void addNewWord() {
        String allWords = "\nfoobar\nbar\n";
        String newWord = "foo";
        AddWords aw = new AddWords();
        String newAllWords = aw.addWord(newWord, allWords);
        String expectedAllWords = "\nfoobar\nbar\nfoo\n";
        Assert.assertEquals(expectedAllWords, newAllWords);
    }
}

回答by Christian Kallas

Or simply,

或者简单地说,

public static void main(String[] args) {
String test = "test";
String test2 = "st";
if (test.contains(test2)) System.out.println("String found");
}

回答by Brian

How about storing the words in an ArrayList and checking if the ArrayList contains the word before adding it? If the order isn't important then use a Set.

如何将单词存储在 ArrayList 中并在添加之前检查 ArrayList 是否包含该单词?如果顺序不重要,则使用 Set。

It'll be a lot easier to work with a collection and you can then convert it to a string when you need to display it. for eg:

使用集合会容易得多,然后您可以在需要显示它时将其转换为字符串。例如:

List wordList = new ArrayList();

public void addWord(String word){
    if(!wordList.contains(word)){
        wordList.add(word);
    }
}

public String displayWordsAsString(){
    StringBuilder builder = new StringBuilder();
    for(int i = 0; i < wordList.size(); i++){
        //add this condition if you only want a new line between words and not every time.
        if(i > 0)
            builder.append("\n");

        builder.append(word); 
    }

    return builder.toString();
}

回答by Joop Eggen

You can use

您可以使用

Set<String> words = LinkedHashSet<String>();

if (words.add("" + letter)) {
    // Added.
}

which maintains the order of adding the words.

它保持添加单词的顺序。