Added function to count occurrences of a char in a string

This commit is contained in:
2020-07-28 01:08:15 -04:00
parent 36cfadea37
commit 7099ce1ae6
2 changed files with 29 additions and 6 deletions

View File

@@ -1,11 +1,11 @@
//src/main/java/mattrixwv/Algorithms.java
//JavaClasses/src/main/java/mattrixwv/Algorithms.java
//Matthew Ellison
// Created: 03-02-19
//Modified: 06-15-20
//Modified: 07-27-20
//This class holds many algorithms that I have found it useful to keep around
//As such all of the functions in here are static and meant to be used as stand alone functions
/*
Copyright (C) 2019 Matthew Ellison
Copyright (C) 2020 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -849,4 +849,8 @@ public class Algorithms{
String swappedString = new String(tempStr);
return swappedString;
}
//This function returns the number of times the character occurs in the string
public static long findNumOccurrence(String str, char c){
return str.chars().filter(ch -> ch == c).count();
}
}

View File

@@ -1,11 +1,11 @@
//src/test/java/mattrixwv/TestAlgorithms.java
//JavaClasses/src/test/java/mattrixwv/TestAlgorithms.java
//Matthew Ellison
// Created: 06-07-20
//Modified: 06-07-20
//Modified: 07-28-20
//This class holds many algorithms that I have found it useful to keep around
//As such all of the functions in here are static and meant to be used as stand alone functions
/*
Copyright (C) 2019 Matthew Ellison
Copyright (C) 2020 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -347,4 +347,23 @@ public class TestAlgorithms{
ArrayList<String> answer = Algorithms.getPermutations(permString);
assertEquals("getPermutations failed", correctAnswer, answer);
}
@Test
public void testFindNumOccurrence(){
//Test 1
String testString = "abcdefgdd";
char testChar = 'a';
long correctAnswer = 1;
long answer = Algorithms.findNumOccurrence(testString, testChar);
assertEquals(correctAnswer, answer);
//Test 2
testChar = 'd';
correctAnswer = 3;
answer = Algorithms.findNumOccurrence(testString, testChar);
assertEquals(correctAnswer, answer);
//Test 3
testChar = 'h';
correctAnswer = 0;
answer = Algorithms.findNumOccurrence(testString, testChar);
assertEquals(correctAnswer, answer);
}
}