1

My String words contains 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 for loop, with w being the word to add.

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.

5
  • 1
    Does that code do what you intend to do? Commented Nov 21, 2012 at 8:50
  • The code does as it should, and letter was a char, so I converted it to String. Commented Nov 21, 2012 at 8:52
  • 2
    you can use regex is you prefer. if the code works and you want to refactor it, then you're probably better off posting at codereview.stackexchange.com Commented Nov 21, 2012 at 8:52
  • @user1778856.. So, you are saying that, you are comparing a single character. And if your string contains it, then you don't add it. For e.g.: - asdf\nasdf\nasf, for this string, your code will fail, if w is a single character. But what you have stated, from that, I would add all the 3 words to the new string. Commented Nov 21, 2012 at 8:58
  • Sorry, for words to add to the string, I meant only words that passed the if (w.contains("" + letter)). I apologize for clarity. Commented Nov 21, 2012 at 9:10

9 Answers 9

3

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

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 w used for.

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.


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 StringBuilder or StringBuffer if I want to modify my string on each iteration.
  • Now, on each iteration, check whether your StringBuilder already contains that word. If it does not contains, then append it, else leave it.
  • At the end of your loop, print your StringBuilder instance.

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

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 ArrayList or Set by iterating over either of them.

Sign up to request clarification or add additional context in comments.

2 Comments

For the first block, I used words.split("\n") for the for-each loop. To check if the array already has the word in it, I used if (w.equals(s)). If the word is already there, it breaks the entire if-block completely. Otherwise it makes it to the words += w + "\n".
@user1778856.. First of all, you never stated, that you want an array here. Secondly, To check whether an array contains a word, you should use if (array.contains(s))
1

I would store the distinct words you are adding in 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();
}      

2 Comments

wow, this is exactly what I wrote to do 5 mins before you! lol
@pawel +1 thinking the same.
1

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();

Comments

1

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

public class 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

Comments

0

You can use

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

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

which maintains the order of adding the words.

Comments

0

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.

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();
}

Comments

0

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");
      }

}

Comments

0

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.

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);
    }
}

Comments

0

Or simply,

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

1 Comment

This does not work in the case the original poster is talking about. If the string is composed of the two words "test" and "string" (i.e. - "test\nstring\n") your test would return true for "st", even though "st" is not one of the full words in the word list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.