1.11M Members

Java: counting characters in a string

 
0
 
package code;

public class CharacterCounter 
{

	/**
	 * int numberOf(String s, char c)
	 * 
	 * Returns the number of time the char c occurs in the String s
	 * 
	 * @param s is the original String
	 * @param c is the char whose count in s we want to determine
	 * @return the number of occurrences of c in s 
	 * 
	 * Some examples:
	 * 
	 * if s is "", then no matter what c is the answer is 0 (zero)
	 * if s is "abcdefg", and c is 'f', then the correct answer is 1
	 * if s is "farfalle", and c is 'f', then the correct answer is 2
	 * 
	 * The only methods you may call on the String s are charAt(int) and length().
	 */
	public int numberOf(String s, char c) 
	{
		return 0;
		
	}
  

	/**
	 * int numberOf(String s, String characters)
	 * 
	 * Returns the number of times any of the chars in the second String occur in the first String
	 * 
	 * if s is "", then no matter what characters is the answer is 0 (zero)
	 * if s is "abcdefg", and characters is "f", then the correct answer is 1
	 * if s is "farfalle", and characters is "alf", then the correct answer is 6
	 * 
	 * Some examples:
	 * 
	 * The only methods you may call on either String are charAt(int) and length().
	 * 
	 * @param s is the original String
	 * @param characters is the String whose constituent character counts in s we want to determine
	 * @return the number of occurrences of the chars in characters in s 
	 */
	public int numberOf(String s, String characters) {
		return 0;
	}
}

Trying to this but need some help!

 
0
 

All I see is an assignment with no effort demonstrated. What have you tried so far? What have you thought about trying? If you don't have real code yet, how about some pseudocode? How about a specific question?

Per our forum rules:
Do provide evidence of having done some work yourself if posting questions from school or work assignments.

 
0
 

try using

String.replaceAll(regex, replacement)

by this you can replace all strings except the one that you want to count then get the length of the string remaining

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: