Count the number of characters in a string
Solution
importjava.util.*;
import java.io.*;
classStringChar {
public static void main(String args[]) throws IOException
{
String ch;
Scanner reader = new Scanner(System.in); // Scanner
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); // Buffer reader Reads text from a character-input stream.
System.out.print(“Enter the Statement: “); // enter the input string
ch=br.readLine(); // reading the input string from the User
System.out.print(“Enter a Character : “);
char c = reader.next(“.”).charAt(0); // Reading the Input character from the user
int k=count(ch,c); // calling the count fucntion
System.out.println(“The number of occurrences of “+c+” in “+ch+” is “+k);
}
public static int count(String ch, char a)
{
int count=0,len=0;
// try
// {
char name[]=ch.toCharArray(); // Converting the input string into a character Array
len=name.length; // to find the length of the array
for(int j=0;j<len;j++) // iterating over the array to find the input char
{
if(name[j]==a)
count++;// making count = count +1 if found the same char in string
}
// }
//catch(Exception ex){}
return count; // return the the number of times char repeats in a string
}
}