March 07, 2024

Java Problem Solution: Count Occurrences of a Character in a String Java


public class CharacterCounter {
    public static void main(String[] args) {
        String str = "Hello, Software and Testing Training Subscriber!";
        char targetChar = 'r';
        System.out.println("String: " + str);
        System.out.println("Character to count: " + targetChar);
        System.out.println("Occurrences: " + countOccurrences(str, targetChar));
    }
    // Count occurrences of a character in a string java, 
    // Considering the character's case
    public static int countOccurrences(String str, char targetChar) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == targetChar) {
                count++;
            }
        }
        return count;
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.