Count the Given Character
by Isai Damier, Android Engineer @ Google

/*********************************************************************
 * Author: Isai Damier
 * Title: Count the Given Character
 * Project: geekviewpoint
 * Package: algorithms
 *
 * Statement:
 *   Given a text and a character, count the frequency of the character.
 *
 * Time Complexity: O(n)
 * 
 ********************************************************************/ 
 public int countGivenChars(String text, char c) {
  int count = 0;
  for (char x : text.toCharArray()) {
    if (c == x) {
      count++;
    }
  }
  return count;
}
package algorithms;

import org.junit.Test;
import static org.junit.Assert.*;

public class StringsTest {

  /**
   * Test of countGivenChars method, of class Strings.
   * 
   * Text from the Rape of Lucrece: Describing Sextus Targquinius on
   * his way to rape Lucretia
   */
  @Test
  public void testCountGivenChars() {
    System.out.println("countGivenChars");
    String text = "As each unwilling portal yields him way, "
            + "Through little vents and crannies of the place "
            + "The wind wars with his torch to make him stay, "
            + "And blows the smoke of it into his face, "
            + "Extinguishing his conduct in this case. "
            + " But his hot heart, which fond desire doth scorch, "
            + " Puffs forth another wind that fires the torch,";
    
    Strings instance = new Strings();
    assertEquals(8, instance.countGivenChars(text, 'l'));
    assertEquals(6, instance.countGivenChars(text, 'u'));
    assertEquals(12, instance.countGivenChars(text, 'c'));
    assertEquals(12, instance.countGivenChars(text, 'r'));
    assertEquals(19, instance.countGivenChars(text, 'e'));
    assertEquals(0, instance.countGivenChars(text, 'z'));
  }
}