0

If I want to compare the amount one word is used to the other, how would I do that?

It wouldn't be str.contains("cat") > str.contains("dog")

So for example:

if(str.contains("cat") == str.contains("dog")){
    System.out.println("true");
  }
else
system.out.print("false");

This would hypothetically print true if cat and dog appear the same amount of times. But obviously it doesn't, what would I have to d, to get it to check?

Maroun
  • 94,125
  • 30
  • 188
  • 241
James
  • 75
  • 1
  • 2
  • 6
  • In order to be completely correct, you would need to use indexOf, substring, ... A simple version with splitting on spaces could help, but what with "dog, " ? – Stultuske Apr 15 '15 at 08:19
  • 2
    Would "hotdog" be counted as "dog" occurence? – Thomas Apr 15 '15 at 08:20
  • possible duplicate of [java regex match count](http://stackoverflow.com/questions/7378451/java-regex-match-count) – LionC Apr 15 '15 at 08:21

5 Answers5

1

String#contains() will return true if the searched string is found at least once, which is done for performance reasons. Thus str.contains("cat") == str.contains("dog") would be true if both cat and dog are found independent of how often they are found.

What you could do is use 2 regular expressions and check the number of matches:

int countWords(String input, String word ) {
  Pattern p = Pattern.compile( "\\b" + word + "\\b" );

  int count = 0;    
  Matcher m = p.matcher( input );
  while( m.find() ) {
    count++;
  }

  return count;
}

Usage:

String str = "dog eats dog but cat eats hotdog";

System.out.println("dogs: " + countWords( str, "dog"));
System.out.println("cats: " + countWords( str, "cat"));

Output:

dogs: 2
cats: 1
Thomas
  • 87,414
  • 12
  • 119
  • 157
1

To count number of ocurrences of a String in another String create a function (extracted from here):

The "split and count" method:

public class CountSubstring {
    public static int countSubstring(String subStr, String str){
        // the result of split() will contain one more element than the delimiter
        // the "-1" second argument makes it not discard trailing empty strings
        return str.split(Pattern.quote(subStr), -1).length - 1;
}

The "remove and count the difference" method:

public static int countSubstring(String subStr, String str){
        return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}

Then you just have to compare:

return countSubstring("dog", phrase) > countSubstring("cat", phrase);

ADDITIONAL INFORMATION

To compare strings use String::equals or String::equalsIgnoreCase if you don't mean uppercase and lowercase.

 string1.equals(string2);
 string1.equalsIgnoreCase(string2);

To find number of ocurrences of a string in another string use indexOf

 string1.indexOf(string2, index);

To see if a string contains another string use contains

 string1.contains(string2);
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • So for example, the string "catxxxdogxxxdogxxxcat" would be true, because cat and god are in the string the same amount of times. So would "catxxdogxx", but if there was more of either one like "catxxcatxxdog" that would be false. – James Apr 15 '15 at 08:28
0

There are many possible solutions for your problem. I won't show you a full solution, but will try to guide you. Here are some:

  1. split the String according to space(s), iterate over the resulted array and increment the counter when you match the String you're looking for.

  2. use a regex that matches exactly the word you're looking for, there are many useful methods in the Matcher and Pattern classes, go through them.

  3. Java 8 Stream tools has countless methods, you can get the result in one line.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

You could get the count in the following way for dog

index = -1;
dogcount = 0;
do {
 index = str.indexOf("dog",index+1);
 if(index > -1)
   dogcount++;
}while(index == -1);

similarly get cat count

HJK
  • 1,382
  • 2
  • 9
  • 19
0

Use Apache Commons StringUtils.CountMatches: - counts the number of occurrences of one String in another

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#countMatches%28java.lang.String,%20java.lang.String%29

Eduardo Yáñez Parareda
  • 9,126
  • 4
  • 37
  • 50