Count Occurrences of a Character Without Using Loop

The string class provides string.replaceAll method, which internally uses a regular expression to find and replace the characters from given string.

package org.wesome.dsalgo;

public class CountOccurrence {
    static int countOccurrence(String string, String ch) {
        int count = string.length() - string.replaceAll(ch, "").length();
        return count;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class CountOccurrenceTest {
    @Test
    void countOccurrenceTest1() {
        String string = "wesome.org";
        String occurrence = "e";
        Assertions.assertEquals(2, CountOccurrence.countOccurrence(string, occurrence));
    }

    @Test
    void countOccurrenceTest2() {
        String string = "aaaaa";
        String occurrence = "a";
        Assertions.assertEquals(5, CountOccurrence.countOccurrence(string, occurrence));
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on