简体   繁体   中英

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

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.

try this one

String text = "ABCabcRRRRRrrr";
int count = text.length() - text.replace("R", "").length();

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());
}
String str = //the actual string
for(int i=0;i<str.length();++i)
{
    if(str.charAt(i)=='R')
    {
        capitalRCount++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM