0

I am trying to count the amount of 'x' characters that are in a string, and print out the number. I end up just counting the number of characters in the string instead. Here is what I have tried:

int count = 0;

for (int j = 0; j < input1.length(); j++)
{
  char character = input1.charAt(j);
  count++;
}

if (indexX != -1)
  {
     System.out.println("x count: "+count);
  } // indexX = input1.indexOf('x');
Inezda1
  • 21
  • 1
  • 2
  • 4

4 Answers4

2

You are not checking if the chacter is x, and then increasing the counter.

if(character == 'x')
  counter++;
shadowfire
  • 106
  • 3
0

You never check what the character is.

char character = input1.charAt(j);
if (character == 'x') {
  count++;
}
Tim Jasko
  • 1,532
  • 1
  • 8
  • 12
0

You need to check if the character is 'x'. This is how you do it :

for (int j = 0; j < input1.length(); j++)
{
  char character = input1.charAt(j);
  if (character == 'x' || character == 'X') {
  count++;
 {
}
Clyme
  • 84
  • 2
  • 12
0

How about comparing length of string pre and post replace, have a look at http://www.rosettacode.org/wiki/Count_occurrences_of_a_substring#Java

Common method that would work everywhere.

Vinay Pandey
  • 8,589
  • 9
  • 36
  • 54