[Q#13432890][A#13433126] How to search a particular character from string and find how many times it occured
https://stackoverflow.com/q/13432890
Store the following sentence in String 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.
Answer
https://stackoverflow.com/a/13433126
APIzation
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);
package com.stackoverflow.api;
public class Human13433126 {
public static int countCharOccurrences(String s, char c) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) count++;
}
return count;
}
}
package com.stackoverflow.api;
/**
* How to search a particular character from string and find how many times it occured
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/13433126">https://stackoverflow.com/a/13433126</a>
*/
public class APIzator13433126 {
public static void searchCharacter(String s, char c) throws Exception {
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);
}
}