0

I have a String of say, length is 5000. I want to find out the number of times the letter 'R' (Case Sensitive) is used. Below are the two passable solution...

  1. Convert to char array, loop it to perform a condition to check and increment a counter.
  2. Use Substring() with the character 'R' to get an array which could fetch a array. So, the total length of the array +1 will be number of times, the 'R' character in the string(This is not a better solution)

Help me out with the efficient solution on the cards for this. Thanks.

Sean Patrick Floyd
  • 284,665
  • 62
  • 456
  • 576

3 Answers3

6

try this one

String text = "ABCabcRRRRRrrr";
int count = text.length() - text.replace("R", "").length();
Pardeep
  • 827
  • 9
  • 18
2

If you're using java >= 8 you can use the Streams:

public static void main(String args[]) {
    String str= "abcderfgtretRetRotpabcderfgtretRetRotp"
    System.out.println(str.chars().filter(c -> c == 'R').count());
}
Romain
  • 161
  • 1
  • 7
0
String str = //the actual string
for(int i=0;i<str.length();++i)
{
    if(str.charAt(i)=='R')
    {
        capitalRCount++;
    }
}
0xDEADBEEF
  • 572
  • 1
  • 5
  • 16