-2

I am trying to find the number of occurrences of each word in string.

For example Sentence=" My home, is my home". The answer is "my"=2; "home"=2; "is"=1

Here is my code:

int count;
count = 0;
String text[] = new String[100];
String Temp[] = new String[100];
text = Text.getText().split("\\W");
Temp = Text.getText().split("\\W");
for (int j = 0;  j < text.length; j++) {
    for (int i = 0; i < text.length; i++) {

        if (text[j].equals(Temp[i])) {
            count += 1;
            System.out.println(text[i] + "-" + count);
        }
    }
}

Input: me.me.me.me Output:

me-1
me-2
me-3
me-4
me-5
me-6
me-7
me-8
me-9
me-10
me-11
me-12
me-13
me-14
me-15
me-16
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Vasilii Say
  • 19
  • 1
  • 1

2 Answers2

3

You can use a HashMap, HashMap<String, Integer> for doing this.

HashMap<String, Integer> map = new HashMap<>();
String sentence = "My home, is my home".toLowerCase();

for(String word : sentence.split("\\W")) {
    if(word.isEmpty()) {
        continue;
    }
    if(map.containsKey(word)) {
        map.put(word, map.get(word)+1);
    }
    else {
        map.put(word, 1);
    }
}

for(Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

Output:

is: 1
my: 2
home: 2

Take a look at this SO post. There you will see something very similar to what you've asked being answered.

Community
  • 1
  • 1
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
0

You can split the String using split()

String[] s;
s = split("."); //Will split a sentence into an array

So if the input is me.me.me.me. S[0] = "me", S[1] = "me" etc.

Then you just find the length of the array to see how many words were in the original String. So.....

count = s.length;
System.out.println(count);

The question you are asking is very convoluted, but I assume you were trying to "count the number of words in a string. I can't post a comment yet because my rep is beginning. But, you already have a working solution... This is not the place to be posting the solution to your own answers to show it off?

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
DarkV1
  • 1,776
  • 12
  • 17
  • I need to count number of each word in sentence. For example Sentence=" My home, is my home". The answer is "my"=2; "home"=2; "is"=1; – Vasilii Say May 01 '16 at 07:42