Search code examples
javastringloopsreplaceall

How replaceAll method in string works


I need to check the number of different characters in one string whose length can be as long as 20,000 and total test cases of <=10,000. I was doing it by replacing the other characters of the string and then checking its length as the below code shows:

 int no7=myString.replaceAll("[^7]","").length();
 int no0_3=myString.replaceAll("[^0-3]","").length();
 int no5_6=myString.replaceAll("[^56]","").length();

I was wondering how the replaceAll method works and whether it would be faster if I do the counting in one single loop checking each character of the string. Thanks in advance.


Solution

  • First of all you can make the replacement much faster by adding a + after the character class (e.g. [^7]+). That will replace consecutive runs of unwanted characters instead of just a single one at a time. Depending on your input string this may gain you a significant performance boost.

    But in your case I wouldn't really replace anything and check the length. What you want is the number of sevens, the number of digits between 0 and 3 and the number of fives and sixes. So just write a single loop that checks those:

    int no7 = 0, no0_3 = 0, no5_6 = 0;
    for (int i = 0; i < myString.length(); i++) {
      char c = myString.charAt(i);
      if (c == '7') no7++;
      if (c >= '0' && c <= '3') no0_3++;
      if (c == '5' || c == '6') no5_6++;
    }
    

    This will be faster because you don't have to construct three individual strings to check their lengths and throw them away again and you also save on the regex construction, parsing and runtime. A simple iteration over every character (which is what the regex must do anyway) therefore cuts down your time to at most a third of the original runtime, if not more.