find how many numberof times a character from a String is repeated in java -


i have string of say, length 5000. want find out number of times letter 'r' (case sensitive) used. below 2 passable solution...

  1. convert char array, loop perform condition check , increment counter.
  2. use substring() character 'r' array fetch array. so, total length of array +1 number of times, 'r' character in string(this not better solution)

help me out efficient solution on cards this. thanks.

if you're using java >= 8 can use streams:

public static void main(string args[]) {     string str= "abcderfgtretretrotpabcderfgtretretrotp"     system.out.println(str.chars().filter(c -> c == 'r').count()); } 

Comments