6. Counting the occurrences of a certain character

A simple solution to this problem consists of the following two steps:

  1. Replace every occurrence of the character in the given string with "" (basically, this is like removing all of the occurrences of this character in the given string).
  2. Subtract the length of the string that was obtained in the first step from the length of the initial string.

The code for this method is as follows:

public static int countOccurrencesOfACertainCharacter(
String str, char ch) {

return str.length() - str.replace(String.valueOf(ch), "").length();
}

The following solution covers Unicode surrogate pairs as well:

public static int countOccurrencesOfACertainCharacter(
String str, String ch) {

if (ch.codePointCount(0, ch.length()) > 1) {
// there is more than 1 Unicode character in the given String
return -1;
}

int result = str.length() - str.replace(ch, "").length();

// if ch.length() return 2 then this is a Unicode surrogate pair
return ch.length() == 2 ? result / 2 : result;
}

Another easy to implement and fast solution consists of looping the string characters (a single traversal) and comparing each character with the given character. Increase the counter by one for every match:

public static int countOccurrencesOfACertainCharacter(
String str, char ch) {

int count = 0;

for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}

return count;
}

The solution that covers the Unicode surrogate pairs is in the code that's bundled with this book. In Java 8 functional style, one solution consists of using filter() or reduce(). For example, using filter() will result in the following code:

public static long countOccurrencesOfACertainCharacter(
String str, char ch) {

return str.chars()
.filter(c -> c == ch)
.count();
}

The solution that covers the Unicode surrogate pairs is in the code that's bundled with this book.

For third-party library support, please consider Apache Commons Lang, StringUtils.countMatches()Spring Framework, StringUtils.countOccurrencesOf(), and Guava, CharMatcher.is().countIn().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.179.100