Solution #1:
- package com.javatutorial;
- import java.util.Scanner;
- public class CountNumberofChars {
- public static void main(String[] args) {
- String str = "";
- Scanner in= new Scanner(System.in);
- System.out.println("Please enter a String");
- str=in.nextLine();
- System.out.println("Please enter a Character");
- String chr=in.next();
- int charCount = str.length() - str.replaceAll("a", "").length();
- System.out.println("Number of occurances of given character:"+charCount);
- }
- }
Output:
- Please enter a String
- Java
- Please enter a Character
- a
- Number of occurances of given character:2
Solution #2:
- package com.javatutorial;
- import java.util.Scanner;
- public class CountNumberofChars {
- public static int countOccurrences(String find, String string)
- {
- int count = 0;
- int indexOf = 0;
- while (indexOf > -1)
- {
- indexOf = string.indexOf(find, indexOf + 1);
- if (indexOf > -1)
- count++;
- }
- return count;
- }
- public static void main(String[] args) {
- int charCount=countOccurrences("a", "Instance of Java");
- System.out.println("Number of occurrences of given character:"+charCount);
- }
- }
Output:
- Number of occurrences of given character: 3
Java experience interview programming questions on Strings
in solution#2
ReplyDeletethe first letter will not be countable,for example "hi this Ram" -in this sentence i want to search letter 'h'(there are 2 h's) but it gives only one ....
while (index > -1) {
index = string.indexOf(find, index);
if (index > -1) {
count++;
index++;
}
}
then it will work
Correct !
ReplyDelete