Home > Mobile >  How to count specific occurrences and letters from a string by creating own method in java
How to count specific occurrences and letters from a string by creating own method in java

Time:09-29

I need to create a method that counts the number of occurrences that happens in string str using string chars and I need to pass these tests that is my assignment so not my code:

@Test
    public void test_count_bothEmptyString() {
        int expected = 0;
        int actual = CCStringsIfAndWhile.count("", "");
        
        assertEquals("Testing count - both empty string", expected, actual);
    }

    @Test
    public void test_count_firstEmptyString() {
        int expected = 0;
        int actual = CCStringsIfAndWhile.count("", "abcdefghijklmnopqrstuvwxyz");
        
        assertEquals("Testing count - first is empty string", expected, actual);
    }

    @Test
    public void test_count_secondEmptyString() {
        int expected = 0;
        int actual = CCStringsIfAndWhile.count("This is a test", "");
        
        assertEquals("Testing count - second is empty string", expected, actual);
    }

    @Test
    public void test_count_one() {
        int expected = 1;
        int actual = CCStringsIfAndWhile.count("This is a test", "abc");
        
        assertEquals("Testing count - 'This is a test', 'abc'", expected, actual);
    }

    @Test
    public void test_count_many() {
        int expected = 6;
        int actual = CCStringsIfAndWhile.count("This is a test", "sapqi");
        
        assertEquals("Testing count - 'This is a test', 'sapqi'", expected, actual);
    }

    @Test
    public void test_count_upperAndLowerCase() {
        int expected = 7;
        int actual = CCStringsIfAndWhile.count("This is another test", "stpq");
        
        assertEquals("Testing count - 'This is another test', 'stpq'", expected, actual);
    }

I've tried something like this however I can't seem to find an if statement that checks each letter of the string:

public static int count(String str, String chars) 
    {
        int count = 0;
        int charCount = 0;
        while(count<str.length()) 
      {
            if() 
            {
                charCount  ;
                return charCount  ;
            }

       else {
                charCount=0;
                
            }

            count  ;
        }
        return charCount;
        
    }

CodePudding user response:

  1. should probably use two loops since you need to iterate through both string to find all occurances of chars of one string in another

  2. return charCount ; definitely not right, the return inside the loop will stop the loop prematurely

  3. judging by your test cases you will need to add an if statement to check for empty string in either inputs and return a 0

Implementing above you get sth like this

 if(str.isEmpty()||chars.isEmpty()){return 0;}
 for (char strChar: str.toCharArray()) {
   for (char chars: chars.toCharArray()) {
      if(strChar==chars){
         charCount  ;
      }
   }
 }

CodePudding user response:

This is what I did and it worked thank you for the help:

    public static int count(String str, String chars) 
    {

        int charCount = 0;
        if(str.isEmpty()||chars.isEmpty()) 
        {
            return 0;
            
        }
        
        for (char strC: str.toCharArray()) 
        {
          for (char charsC: chars.toCharArray()) 
          {
             if(Character.toLowerCase(strC)==Character.toLowerCase(charsC)) 
             {
                charCount  ;

             }
          }
        }
        return charCount;

CodePudding user response:

Here are my suggestions. You can do this by using several methods of the String API

  • Have the variable count index a character in chars. You can use charAt (count) to index a single character.
  • That means your while loop will run while count < chars.length, instead of str.length.
  • You will need an inner loop, in case str has more than one occurrence of the current character from chars.
  • You can use an indexOf method to search str for the current character from chars.
  • Keep track of the current search starting position in str, and update it for the next search whenever indexOf returns a non-negative.
  • You can use an indexOf method that takes a starting position or use a substring method.
  • I don't think you want else { charCount=0;}. You want the total, so each time you find a match, you increment charCount. You don't set it to zero, except before the loop, which you did.

Other suggestions:

  • In my opinion, using a for loop where you have the while loop makes the code more readable. I generally use a for loop when the number of iterations is determined at the start of the loop, which seems to be the case in your program. I use a while or a do ... while when the number of iterations is indefinite.

--

  • You could create a helper method that counts the number of occurrences of a character in a string. During the loop, for each character in chars, call the helper method.
  • The helper method might look like public static int charCounter (String str, char c). Your count method would have one loop, and charCounter would have one loop.
  • You can use toCharArray to convert a String to a char [].

--

  • A better name for count might be charsIndex.
  • Related