How to count number of characters in a string ?

  • To count the amount of ‘x’ characters that are in a string, and print out the number using java program.
class Wikitechy
{
// Method that return count of the given
// character in the string
public static int count(String s, char c)
{
int res = 0;

for (int i=0; i<s.length(); i++)
{
// checking character in string
if (s.charAt(i) == c)
res++;
}
return res;
}

// Driver method
public static void main(String args[])
{
String str= "Welcome to Wikitechy";
char c = 'W';
System.out.println(count(str, c));
}
}

Output

2

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,