这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.baeldung.splitstringtointarray;

public class SplitStringToIntArray {

public int[] convert(String numbers, String delimiterRegex) {
if (numbers == null || numbers.isEmpty()) {
return new int[0];
}

String[] parts = numbers.split(delimiterRegex);
int[] intArray = new int[parts.length];

for (int i = 0; i < parts.length; i++) {
intArray[i] = Integer.parseInt(parts[i].trim());
}

return intArray;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.baeldung.splitstringtointarray;

import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;

class StringToIntArrayConverterUnitTest {

private final SplitStringToIntArray converter = new SplitStringToIntArray();

@Test
void givenCommaSeparatedString_whenConvert_thenReturnIntArray() {
int[] result = converter.convert("10, 20, 30, 40, 50", ",");
assertThat(result).containsExactly(10, 20, 30, 40, 50);
}

@Test
void givenSemicolonSeparatedString_whenConvert_thenReturnIntArray() {
int[] result = converter.convert("10; 20; 30; 40; 50", ";");
assertThat(result).containsExactly(10, 20, 30, 40, 50);
}

@Test
void givenPipeSeparatedString_whenConvert_thenReturnIntArray() {
int[] result = converter.convert("10|20|30|40|50", "\\|");
assertThat(result).containsExactly(10, 20, 30, 40, 50);
}

@Test
void givenEmptyString_whenConvert_thenReturnEmptyArray() {
int[] result = converter.convert("", ",");
assertThat(result).isEmpty();
}
}