Count character occurrences in a string ?

Count character occurrences in a string ?

Asked on October 26, 2018 in String.
Add Comment


  • 2 Answer(s)

    1. Imperative Approach:
    Some developers may prefer to use core Java. There are many ways for counting the number of occurrences of a char in a String.

    Let’s start with a simple/naive approach:

    String someString = “elephant”;
    char someChar = ‘e’;
    int count = 0;

    for (int i = 0; i = someString.length()) {
    return 0;
    }

    int count = someString.charAt(index) == searchedChar ? 1 : 0;
    return count + countOccurences(
    someString, searchedChar, index + 1);
    }
    We can invoke this recursive method in the following way: useRecursionToCountChars(“elephant”, ‘e’, 0)

    Answered on February 5, 2019.
    Add Comment

    1. Imperative Approach
    Some developers may prefer to use core Java. There are many ways for counting the number of occurrences of a char in a String.

    Let’s start with a simple/naive approach:

    String someString = “elephant”;
    char someChar = ‘e’;
    int count = 0;

    for (int i = 0; i = someString.length()) {
    return 0;
    }

    int count = someString.charAt(index) == searchedChar ? 1 : 0;
    return count + countOccurences(
    someString, searchedChar, index + 1);
    }
    We can invoke this recursive method in the following way: useRecursionToCountChars(“elephant”, ‘e’, 0)

    Answered on February 5, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.