1
+ package com .baeldung .splitbylastoccurrence ;
2
+
3
+ import static org .junit .jupiter .api .Assertions .assertArrayEquals ;
4
+
5
+ import org .junit .jupiter .api .Test ;
6
+
7
+ public class SplitByTheLastOccurrenceOfACharUnitTest {
8
+
9
+ private static final String INPUT1 = "a b c@e f g@x y z" ;
10
+ private static final String [] EXPECTED1 = new String [] { "a b c@e f g" , "x y z" };
11
+
12
+ private static final String INPUT2 = "@a b c" ;
13
+ private static final String [] EXPECTED2 = new String [] { "" , "a b c" };
14
+
15
+ private static final String INPUT3 = "a b c@" ;
16
+ private static final String [] EXPECTED3 = new String [] { "a b c" , "" };
17
+
18
+ private static final String INPUT4 = "a b c" ;
19
+ private static final String [] EXPECTED4 = new String [] { "a b c" };
20
+
21
+ public String [] splitByLastOccurrence (String input , char character ) {
22
+ int idx = input .lastIndexOf (character );
23
+ if (idx < 0 ) {
24
+ return new String [] { input };
25
+ }
26
+ return new String [] { input .substring (0 , idx ), input .substring (idx + 1 ) };
27
+ }
28
+
29
+ @ Test
30
+ void whenUsingSplitByLastOccurrence_thenCorrect () {
31
+ String [] result1 = splitByLastOccurrence (INPUT1 , '@' );
32
+ assertArrayEquals (EXPECTED1 , result1 );
33
+
34
+ String [] result2 = splitByLastOccurrence (INPUT2 , '@' );
35
+ assertArrayEquals (EXPECTED2 , result2 );
36
+
37
+ String [] result3 = splitByLastOccurrence (INPUT3 , '@' );
38
+ assertArrayEquals (EXPECTED3 , result3 );
39
+
40
+ String [] result4 = splitByLastOccurrence (INPUT4 , '@' );
41
+ assertArrayEquals (EXPECTED4 , result4 );
42
+ }
43
+
44
+ @ Test
45
+ void whenUsingSplitWithDefaultLimit_thenNotWorkingForInput3 () {
46
+ String regex = "@(?=[^@]*$)" ;
47
+
48
+ String [] result1 = INPUT1 .split (regex );
49
+ assertArrayEquals (EXPECTED1 , result1 );
50
+
51
+ String [] result2 = INPUT2 .split (regex );
52
+ assertArrayEquals (EXPECTED2 , result2 );
53
+
54
+ String [] result3 = INPUT3 .split (regex );
55
+ assertArrayEquals (new String [] { "a b c" }, result3 );
56
+
57
+ String [] result4 = INPUT4 .split (regex );
58
+ assertArrayEquals (EXPECTED4 , result4 );
59
+ }
60
+
61
+ @ Test
62
+ void whenUsingSplitWithLimit_thenCorrect () {
63
+ String regex = "@(?=[^@]*$)" ;
64
+
65
+ String [] result1 = INPUT1 .split (regex , 2 );
66
+ assertArrayEquals (EXPECTED1 , result1 );
67
+
68
+ String [] result2 = INPUT2 .split (regex , 2 );
69
+ assertArrayEquals (EXPECTED2 , result2 );
70
+
71
+ String [] result3 = INPUT3 .split (regex , 2 );
72
+ assertArrayEquals (EXPECTED3 , result3 );
73
+
74
+ String [] result4 = INPUT4 .split (regex , 2 );
75
+ assertArrayEquals (EXPECTED4 , result4 );
76
+
77
+ }
78
+ }
0 commit comments