1+ package com .baeldung .countseq ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4+
5+ import java .util .regex .Matcher ;
6+ import java .util .regex .Pattern ;
7+
8+ import org .apache .commons .lang3 .StringUtils ;
9+ import org .junit .jupiter .api .Test ;
10+
11+ public class CountSequenceInStringUnitTest {
12+
13+ private final static String INPUT = "This is a test string. This test is for testing the count of a sequence in a string. This string has three sentences." ;
14+
15+ int countSeqByIndexOf (String input , String seq ) {
16+ int count = 0 ;
17+ int index = input .indexOf (seq );
18+ while (index != -1 ) {
19+ count ++;
20+ index = input .indexOf (seq , index + seq .length ());
21+ }
22+ return count ;
23+ }
24+
25+ @ Test
26+ void whenUsingIndexOf_thenCorrect () {
27+ assertEquals (3 , countSeqByIndexOf (INPUT , "string" ));
28+ assertEquals (2 , countSeqByIndexOf (INPUT , "string." ));
29+ }
30+
31+ int countSeqByRegexFind (String input , String seq ) {
32+ // Alternative: Pattern pattern = Pattern.compile(seq, Pattern.LITERAL);
33+ Matcher matcher = Pattern .compile (Pattern .quote (seq ))
34+ .matcher (input );
35+ int count = 0 ;
36+ while (matcher .find ()) {
37+ count ++;
38+ }
39+ return count ;
40+ }
41+
42+ @ Test
43+ void whenUsingRegexFind_thenCorrect () {
44+ assertEquals (3 , countSeqByRegexFind (INPUT , "string" ));
45+ assertEquals (2 , countSeqByRegexFind (INPUT , "string." ));
46+ }
47+
48+ int countSeqByRegexSplit (String input , String seq ) {
49+ Pattern pattern = Pattern .compile (seq , Pattern .LITERAL );
50+ return pattern .split (input , -1 ).length - 1 ;
51+ }
52+
53+ @ Test
54+ void whenUsingRegexSplit_thenCorrect () {
55+ assertEquals (3 , countSeqByRegexSplit (INPUT , "string" ));
56+ assertEquals (2 , countSeqByRegexSplit (INPUT , "string." ));
57+ }
58+
59+ int countSeqByStream (String input , String seq ) {
60+ long count = Pattern .compile (Pattern .quote (seq ))
61+ .matcher (input )
62+ .results ()
63+ .count ();
64+ return Math .toIntExact (count );
65+ }
66+
67+ @ Test
68+ void whenUsingStream_thenCorrect () {
69+ assertEquals (3 , countSeqByStream (INPUT , "string" ));
70+ assertEquals (2 , countSeqByStream (INPUT , "string." ));
71+ }
72+
73+ @ Test
74+ void whenUsingApacheCommonsLangCountMatches_thenCorrect () {
75+ assertEquals (3 , StringUtils .countMatches (INPUT , "string" ));
76+ assertEquals (2 , StringUtils .countMatches (INPUT , "string." ));
77+ }
78+ }
0 commit comments