-1

How do I code a method which expects a string and prints the count of number of occurrences of the words in the sentence passed to the method.

Sample Input/Output :

Input : My Name is good and I like my name
Expected Output :
I - 1
Name - 2

How do I find the count of number of occurrences of the words?

I have tried this so far:

public class Problem1 {
    public void testmethod(){
    List<String> inputStr = new List<String>();
    String inputStr[]  = inputStr.split('');
    Set<String> SetString = new Set<String>(inputStr);

        for(String str : inputStr ){

        }
    }
}

closed as off-topic by glls, Sebastian Kessel, Lukas Lunow, Raul, Derek F May 15 at 12:34

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions on problems in code you've written must describe the specific problem and include valid code to reproduce it. For help writing short, self-contained syntactically-valid examples, see: SSCCE.org" – glls, Sebastian Kessel, Lukas Lunow, Raul, Derek F
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    What have you tried so far? Where are you stuck? Please take a quick look at How to Ask and come back to edit your question. – David Reed May 14 at 16:22
2

You would use a Map for this purpose.

Map<String, Integer> wordCounts = new Map<String, Integer>();
for(String word: inputStr.split('\\s+')) {
  Integer wordCount = wordCounts.get(word);
  if(wordCount == null) {
    wordCount = 0;
  }
  wordCounts.put(word, wordCount+1);
}

If case-sensitivity does not matter, make sure you convert to a common case:

Map<String, Integer> wordCounts = new Map<String, Integer>();
for(Sting word: inputStr.toLowerCase().split('\\s+')) {
  Integer wordCount = wordCounts.get(word);
  if(wordCount == null) {
    wordCount = 0;
  }
  wordCounts.put(word, wordCount+1);
}

The output would look like this:

{and=1, good=1, i=1, is=1, like=1, my=2, name=2}

  • For performance I would do the toLowerCase once before splitting the string. – Phil W May 14 at 17:04
  • @PhilW For small payloads, it wouldn't matter significantly, but I totally agree that would be the preferred way to do so. I've edited this answer to reflect that. – sfdcfox May 14 at 17:08
0

There is an APEX string method that does exactly this:

APEX string methods

countMatches(substring) Returns the number of times the specified substring occurs in the current String. Signature public Integer countMatches(String substring)

So in your case:

String input = "My name is good and I like my name";
String subStr = "I";

input.countMatches(subStr); //should return 1

String subStr = "name";

input.countMatches(subStr); //should return 2
  • This pre-supposes you know the word(s) to count. sfdcfox's version meets the stated requirement. – Phil W May 14 at 17:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.