0

I need some help with java comparator. I need to compare strings by the number of words they contain.

For example, "hello" comes before "I see" which comes before "I see you".

Anyone got any ideas how I would do this? Thank you in advance for any help you could give.

1

4 Answers 4

3
import java.util.Comparator;
import java.util.StringTokenizer;

public class WordCountComparator implements Comparator<String> {
    public int compare(String str1, String str2) {
        if (str1 == str2 || (str1 == null && str2 == null)) {
            return 0;
        } else if (str1 == null) {
            return -1;
        } else if (str2 == null) {
            return 1;
        }

        int len1 = new StringTokenizer(str1, " \t\r\n").countTokens();
        int len2 = new StringTokenizer(str2, " \t\r\n").countTokens();
        return len1 < len2 ? -1 : len1 == len2 ? 0 : 1;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Using regular expressions is tricky and may be not a robust solution, prefer BreakIterator.
@David Olivan Ubetio: This solution does not use regular expressions.
Agreed that regular expressions are not robust, and they're expensive. Edited answer to avoid using them in String.split() and use StringTokenizer.countTokens() in favor.
1

Write a comparator for a String type. In the compareTo method, simply call string.split(" ") to break it down to 'words' (if that's sufficient), then return the comparison between those two integers.

Comments

1

string.split(" ") will return an array, where each element is a word. So comparing the number of elements in the array would give you a rough implementation of this. Obviously you may need to handle line-breaks, tabs etc., so keep that in mind.

Apache commons also has some useful methods to do this.

2 Comments

Better to use BreakIterator to separate words.
Wow, how have I never seen that class. I agree, +1.
0
 public class StringComparator implements Comparator<String> {

      public int compare(String o1, String o2) {
        if(o1==null && o2 ==null)
        return 0;
        String[] bo1 = o1.split("\\s");
        String[] bo2 = o2.split("\\s");
        return bo1.length >= bo2.length ? bo1.length > bo2.length ? 1 : 0 : -1;
      }
}

Comments

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.