Saturday, 17 August 2013

Finding a repeated character in a string

Finding a repeated character in a string

The problem states the following: given a string and a character by the
user find the number of times the character (given by the user) repeats
itself in the string (also given by the user).
I have this piece of code
public int repeticion (int s){
int return = 0;
int cont = 0;
Scanner in = new Scanner(System.in);
System.out.println("Write a string: ");
String chain = in.next();
System.out.println("Write the character: ");
String character = in.next();
if (chain.contains(character)) {
cont = cont + 1;
}
System.out.println("The character repeats itself "+cont+"times");
return return;
But as you can see the .contains only counts the character once, not the
number of times it appears in the string.

No comments:

Post a Comment