2021年5月1日星期六

Count occurrence of a character

Raji wants to count the no of occurrences of the given character. Write a 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  

I have done like this

import java.util.*;  import java.util.regex.*;    public class OccurrenceOfChar {        public static void main(String[] args){          Scanner sc=new Scanner(System.in);          // Fill the code          System.out.println("Enter a word:");          String str=sc.next();          sc.nextLine();          System.out.println("Enter the character:");          char c=sc.next().charAt(0);          int res=0;                              if(str.matches("\\w\\s")==false){              if(Character.isAlphabetic(c)){                  str=str.replace(" ","");                  for(int i=0;i<str.length();i++){                      if(str.charAt(i)==c){                          res++;                      }                  }                  if(res!=0){                      System.out.println("No of '"+c+"' present in the given word is "+res+".");                  }                  else{                      System.out.println("The given character '"+c+"' is not present in the given word.");                  }              }else{                  System.out.println("Given character is not an alphabet");              }          }else{              System.out.println("Not a valid string");          }            //            }    }  

but i am getting errors

Failed tests  Test 2: Check the logic when character is not present  Test 3: Check the logic when character is not present and word is in capital  Test 5: Check the logic when the word is invalid  Test 8: Check the logic when the word has no alphabets  Test 1: Check the logic when character is present  
https://stackoverflow.com/questions/67351018/count-occurrence-of-a-character May 02, 2021 at 05:30AM

没有评论:

发表评论