-3

I am supposed to find how many times the word occurred in a given line of a sentence without using API, except .charAt. Any help would be great! thank you

Ex of input:

dog

My dog is very cute dog

Every dog passes by another dog, dogs will bark at another dog

They are very cute

Ex of a word:

dog

Final output: 1 in line 1, 2 in line 2, 4 in line 3, 0 in line 4.

I was able to get the howManyTimes output by checking the first letter, but I can't figure out how I can check for ALL of the characters to be the same as the word.

public void calculation(String input, String word, int count)
{
    howManyTimes=0;
    line = count + "";
    int counter = 0;
    for(int i = 0; i < input.length() - word.length(); i++)
    {
        for(int j = 0; j < word.length(); j++)
        {
            if(word.charAt(j) == input.charAt(i+j))
            {
                counter++;
                if(word.length()==counter)
                {
                    howManyTimes++;
                }
            }
        }
    }
}
Community
  • 1
  • 1
Aero Hun
  • 11
  • 2

1 Answers1

1

You are almost there:

  1. condition input.length() - word.length() loses one dog (at the end of line)
  2. you have to be careful how you define word (your example does not separate words do "dodog" will include single "dog" word.
  3. please zero your counter - or declare inside loop like below:

corrected code:

public int calculation(String input, String word)
{
      int howManyTimes = 0;
      for(int i = 0; i < input.length() - word.length() + 1; i++)
      {
          int counter = 0;         
          for(int j = 0; j < word.length() && word.charAt(j) == input.charAt(i+j); j++)
          {
              counter++;
          }
          if (word.length() == counter) {
              howManyTimes++;
          }
      }
      return howManyTimes;
}
Maciej
  • 1,954
  • 10
  • 14
  • 1
    Thank you! I've tried many different logic inside the nested for loops, but it seems like +1 was the only problem. – Aero Hun Mar 13 '18 at 12:18