1,105,406 Community Members

Java: counting characters in a string

Member Avatar
willywhomperz
Newbie Poster
11 posts since Jul 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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!

Member Avatar
Ezzaral
Posting Sage
7,431 posts since May 2007
Reputation Points: 2,714 [?]
Q&As Helped to Solve: 953 [?]
Skill Endorsements: 31 [?]
Moderator
Featured
 
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.

Member Avatar
dimasalang
Junior Poster in Training
76 posts since Nov 2010
Reputation Points: 1 [?]
Q&As Helped to Solve: 12 [?]
Skill Endorsements: 3 [?]
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: