In: Computer Science
public class StringTools {
public static int count(String a, char c) {
}
According to the question, we have to design a static method which will count the number of occurrence of a character in a given string, the complete java code is as follows:-
import java.util.*;
public class StringTools
{
public static int count(String a, char c)
{
int count = 0;
for (int i = 0; i < a.length(); i++)
{
if (a.charAt(i) == c)
count++;
}
return count;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
System.out.print("Enter a character: ");
char a = sc.next().charAt(0);
int res =StringTools.count(str, a);
System.out.println("The letter " + a + " in string " + str +" was
found " + res+" times");
}
}
The output of the above code is as follows:-
Enter a string: banana
Enter a character: n
The letter n in string banana was found 2 times
The screenshot of the above code is as follows:-