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
  • 292,901
  • 67
  • 465
  • 588

3 Answers3

6

try this one

String text = "ABCabcRRRRRrrr";
int count = text.length() - text.replace("R", "").length();
Pardeep
  • 945
  • 10
  • 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
  • 301
  • 2
  • 7
0
String str = //the actual string
for(int i=0;i<str.length();++i)
{
    if(str.charAt(i)=='R')
    {
        capitalRCount++;
    }
}
0xDEADBEEF
  • 590
  • 1
  • 5
  • 16