-4

Store the following sentence in String

“JAVA IS TOUGH LANGUAGE" 

I would like to ask a user to provide a character as an input and then print the total number of occurrence of that character in the above sentence. Moreover if a user wants to search a particular phrase or character in string he/she should able to search it.

Please tell me the simple way of beginners.

OmnipotentEntity
  • 16,531
  • 6
  • 62
  • 96
user1832150
  • 11
  • 1
  • 1
  • 4

3 Answers3

2
  String s ="JAVA IS TOUGH LANGUAGE";
       char c ='A'; //character c is static...can be modified to accept user input
    int cnt =0;
    for(int i=0;i<s.length();i++)
        if(s.charAt(i)==c)
            cnt++;
    System.out.println("No of Occurences of character "+c+"is"+cnt);
scanE
  • 332
  • 4
  • 19
1

The calculation can be done in one line:

String sentence ="JAVA IS TOUGH LANGUAGE";
String letter = "x"; // user input

int occurs = sentence.replaceAll("[^" + letter + "]", "").length();

This works by replacing every character that is not the letter (using the regex [^x]) with a blank (effectively deleting it), then looking at the length of what's left.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

This version the user would pass in the character they wish to search for. So for example, from the command line they would call the program like so:

java TestClass A

This would search for "A" in the string.

public class TestClass {
  static String searchString = "JAVA IS TOUGH LANGUAGE";
  static public void main(String[] args) {
    int answer = 0;
    if(args.length > 0){
        char searchChar = args[0].charAt(0);
        for (int i = 0; i < searchString.length(); i++){
            if (searchString.charAt(i) == searchChar){
                answer += 1;
            }
        }
    }
    System.out.println("Number of occurences of " + args[0] + " is " + answer);
  }
}
Penelope The Duck
  • 656
  • 1
  • 7
  • 16