Skip to content

Commit 1226e41

Browse files
count occurrence of a given character in String?
count occurrence of a given character in String? (solution) if asked count occurrence of more than one character than you can either use an array, hash table or any additional data structure. In order to solve this problem, you are not allowed to do so. Your method must return count of given character, for example if input String is "Java" and given character is 'a' then it should return 2. Bonus point if you handle case, null and empty String and come up with unit tests.
1 parent cc2a708 commit 1226e41

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Challenge08.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package challenge08;
2+
3+
import static org.junit.Assert.assertTrue;
4+
import java.util.regex.Pattern;
5+
import org.junit.Test;
6+
7+
/**
8+
* The Class Challenge08.
9+
*
10+
* count occurrence of a given character in String?
11+
*/
12+
public class Challenge08 {
13+
14+
/**
15+
* Count.
16+
*
17+
* @param input the input
18+
* @param c the c
19+
* @return the int
20+
*/
21+
public static int count(String input, char c) {
22+
int count = 0;
23+
24+
for (int i = 0; i < input.length() - 1; i++) {
25+
if (input.charAt(i) == c) {
26+
count++;
27+
}
28+
}
29+
return count;
30+
}
31+
32+
/**
33+
* Test.
34+
*/
35+
@Test
36+
public void test() {
37+
assertTrue(2 == (Challenge08.count("{Programming", 'm')));
38+
39+
}
40+
}

0 commit comments

Comments
 (0)