Skip to content

Commit f9277b3

Browse files
sanesaipivovarit
authored andcommitted
Add examples for substring operations (eugenp#5139)
1 parent a2f77a2 commit f9277b3

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.baeldung.string;
2+
3+
import java.util.Scanner;
4+
import java.util.regex.Matcher;
5+
import java.util.regex.Pattern;
6+
7+
import org.apache.commons.lang3.StringUtils;
8+
import org.junit.Assert;
9+
import org.junit.Test;
10+
11+
public class SubstringUnitTest {
12+
13+
String text = "Julia Evans was born on 25-09-1984. She is currently living in the USA (United States of America).";
14+
15+
@Test
16+
public void givenAString_whenUsedStringUtils_ShouldReturnProperSubstring() {
17+
Assert.assertEquals("United States of America", StringUtils.substringBetween(text, "(", ")"));
18+
Assert.assertEquals("the USA (United States of America).", StringUtils.substringAfter(text, "living in "));
19+
Assert.assertEquals("Julia Evans", StringUtils.substringBefore(text, " was born"));
20+
}
21+
22+
@Test
23+
public void givenAString_whenUsedScanner_ShouldReturnProperSubstring() {
24+
try (Scanner scanner = new Scanner(text)) {
25+
scanner.useDelimiter("\\.");
26+
Assert.assertEquals("Julia Evans was born on 25-09-1984", scanner.next());
27+
}
28+
}
29+
30+
@Test
31+
public void givenAString_whenUsedSplit_ShouldReturnProperSubstring() {
32+
String[] sentences = text.split("\\.");
33+
Assert.assertEquals("Julia Evans was born on 25-09-1984", sentences[0]);
34+
}
35+
36+
@Test
37+
public void givenAString_whenUsedRegex_ShouldReturnProperSubstring() {
38+
Pattern pattern = Pattern.compile("\\d{2}\\-\\d{2}-\\d{4}");
39+
Matcher matcher = pattern.matcher(text);
40+
41+
if (matcher.find()) {
42+
Assert.assertEquals("25-09-1984", matcher.group());
43+
}
44+
}
45+
46+
@Test
47+
public void givenAString_whenUsedSubSequence_ShouldReturnProperSubstring() {
48+
Assert.assertEquals("USA (United States of America)", text.subSequence(67, text.length() - 1));
49+
}
50+
51+
@Test
52+
public void givenAString_whenUsedSubstring_ShouldReturnProperSubstring() {
53+
Assert.assertEquals("USA (United States of America).", text.substring(67));
54+
Assert.assertEquals("USA (United States of America)", text.substring(67, text.length() - 1));
55+
}
56+
57+
@Test
58+
public void givenAString_whenUsedSubstringWithIndexOf_ShouldReturnProperSubstring() {
59+
Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')')));
60+
}
61+
62+
}

0 commit comments

Comments
 (0)