init commit (#11623)

This commit is contained in:
Azhwani 2022-01-03 05:13:38 +01:00 committed by GitHub
parent cf49235b4e
commit 148627f1d0
2 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,51 @@
package com.baeldung.split;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
public class SplitStringEveryNthChar {
public static List<String> usingSplitMethod(String text, int n) {
String[] results = text.split("(?<=\\G.{" + n + "})");
return Arrays.asList(results);
}
public static List<String> usingSubstringMethod(String text, int n) {
List<String> results = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += n) {
results.add(text.substring(i, Math.min(length, i + n)));
}
return results;
}
public static List<String> usingPattern(String text, int n) {
List<String> results = new ArrayList<>();
Pattern pattern = Pattern.compile(".{1," + n + "}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String match = text.substring(matcher.start(), matcher.end());
results.add(match);
}
return results;
}
public static List<String> usingGuava(String text, int n) {
Iterable<String> parts = Splitter.fixedLength(n)
.split(text);
return ImmutableList.copyOf(parts);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.split;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import java.util.List;
import org.junit.jupiter.api.Test;
public class SplitStringEveryNthCharUnitTest {
public static final String TEXT = "abcdefgh123456";
@Test
public void givenString_whenUsingSplit_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingSplitMethod(TEXT, 3);
assertThat(results, contains("abc", "def", "gh1", "234", "56"));
}
@Test
public void givenString_whenUsingSubstring_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingSubstringMethod(TEXT, 4);
assertThat(results, contains("abcd", "efgh", "1234", "56"));
}
@Test
public void givenString_whenUsingPattern_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingPattern(TEXT, 5);
assertThat(results, contains("abcde", "fgh12", "3456"));
}
@Test
public void givenString_whenUsingGuava_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingGuava(TEXT, 6);
assertThat(results, contains("abcdef", "gh1234", "56"));
}
}