Computer Science, asked by Kristen3572, 25 days ago

Raji wants to count the no of occurrences of the given character. Write
program to accept a word from the user. Get a character from the user and find the no of occurrences .
Check whether the given character and word is valid
The word is valid if it contains only alphabets and no space or any special characters or numbers.
The character is valid if it is an alphabet alone.
Sample Input 1:
Enter a word:
programming
Enter the character:
m
Sample Output 1:
No of 'm' present in the given word is 2.
Sample Input 2:
Enter a word:
programming
Enter the character:
s
Sample Output 2:
The given character 's' not present in the given word.
Sample Input 3:
Enter a word:
56
Sample Output 3:
Not a valid string
Sample Input 4:
Enter a word:
Hello
Enter the character:
6
Sample Output 4:
Given character is not an alphabet

Answers

Answered by avinashacharya500
6

Answer:

import java.util.*;

import java.util.regex.Pattern;

class OccurrenceOfChar

{

public static int count(String s, char c)

{

int res = 0;

for (int i=0; i<s.length(); i++)

{

if (s.charAt(i) == c)

res++;

}

return res;

}

public static void main(String args[])

{

Scanner sc= new Scanner(System.in);

System.out.print("Enter a word: ");

String str= sc.nextLine();

if(Pattern.matches("^[a-zA-Z]*$",str) && (!str.isEmpty())){

System.out.print("Enter the character: ");

char c = sc.next().charAt(0);

if(Character.isAlphabetic(c)){

if( str.indexOf(c)==-1){

System.out.println("The given character '"+c+"' not present in the given word.");

}else {

System.out.println("No of '"+c+ "' present in the given word is " +count(str, c)+".");

}

}

else{

System.out.println("Given character is not an alphabet");

}

}else{

System.out.println("Not a valid string");

}

}

}

Explanation:

Similar questions