mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 01:35:16 +08:00
test: CountCharTest
(#5423)
test: CountCharTest Co-authored-by: alxkm <alx@alx.com>
This commit is contained in:
@ -5,13 +5,16 @@ public final class CountChar {
|
||||
}
|
||||
|
||||
/**
|
||||
* Count non space character in string
|
||||
* Counts the number of non-whitespace characters in the given string.
|
||||
*
|
||||
* @param str String to count the characters
|
||||
* @return number of character in the specified string
|
||||
* @param str the input string to count the characters in
|
||||
* @return the number of non-whitespace characters in the specified string;
|
||||
* returns 0 if the input string is null
|
||||
*/
|
||||
|
||||
public static int countCharacters(String str) {
|
||||
if (str == null) {
|
||||
return 0;
|
||||
}
|
||||
return str.replaceAll("\\s", "").length();
|
||||
}
|
||||
}
|
||||
|
@ -2,15 +2,23 @@ package com.thealgorithms.others;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
class CountCharTest {
|
||||
|
||||
@Test
|
||||
void testCountCharacters() {
|
||||
String input = "12345";
|
||||
int expectedValue = 5;
|
||||
@ParameterizedTest(name = "\"{0}\" should have {1} non-whitespace characters")
|
||||
@CsvSource({"'', 0", "' ', 0", "'a', 1", "'abc', 3", "'a b c', 3", "' a b c ', 3", "'\tabc\n', 3", "' a b\tc ', 3", "' 12345 ', 5", "'Hello, World!', 12"})
|
||||
@DisplayName("Test countCharacters with various inputs")
|
||||
void testCountCharacters(String input, int expected) {
|
||||
assertEquals(expected, CountChar.countCharacters(input));
|
||||
}
|
||||
|
||||
assertEquals(expectedValue, CountChar.countCharacters(input));
|
||||
@Test
|
||||
@DisplayName("Test countCharacters with null input")
|
||||
void testCountCharactersNullInput() {
|
||||
assertEquals(0, CountChar.countCharacters(null));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user