Skip to content

Commit 1961fae

Browse files
authored
Merge pull request #18878 from tecofers/BAEL-9480-string-to-int-array
BAEL-9480: Add code for article: Splitting String and Put It on int A…
2 parents 669574c + 785c721 commit 1961fae

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.splitstringtointarray;
2+
3+
public class SplitStringToIntArray {
4+
5+
public int[] convert(String numbers, String delimiterRegex) {
6+
if (numbers == null || numbers.isEmpty()) {
7+
return new int[0];
8+
}
9+
10+
String[] parts = numbers.split(delimiterRegex);
11+
int[] intArray = new int[parts.length];
12+
13+
for (int i = 0; i < parts.length; i++) {
14+
intArray[i] = Integer.parseInt(parts[i].trim());
15+
}
16+
17+
return intArray;
18+
}
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.splitstringtointarray;
2+
3+
import org.junit.jupiter.api.Test;
4+
import static org.assertj.core.api.Assertions.assertThat;
5+
6+
class StringToIntArrayConverterUnitTest {
7+
8+
private final SplitStringToIntArray converter = new SplitStringToIntArray();
9+
10+
@Test
11+
void givenCommaSeparatedString_whenConvert_thenReturnIntArray() {
12+
int[] result = converter.convert("10, 20, 30, 40, 50", ",");
13+
assertThat(result).containsExactly(10, 20, 30, 40, 50);
14+
}
15+
16+
@Test
17+
void givenSemicolonSeparatedString_whenConvert_thenReturnIntArray() {
18+
int[] result = converter.convert("10; 20; 30; 40; 50", ";");
19+
assertThat(result).containsExactly(10, 20, 30, 40, 50);
20+
}
21+
22+
@Test
23+
void givenPipeSeparatedString_whenConvert_thenReturnIntArray() {
24+
int[] result = converter.convert("10|20|30|40|50", "\\|");
25+
assertThat(result).containsExactly(10, 20, 30, 40, 50);
26+
}
27+
28+
@Test
29+
void givenEmptyString_whenConvert_thenReturnEmptyArray() {
30+
int[] result = converter.convert("", ",");
31+
assertThat(result).isEmpty();
32+
}
33+
}

0 commit comments

Comments
 (0)