BAEL-7514: Get first n characters in a String in Java (#15817)
This commit is contained in:
parent
80bc3342ff
commit
8059f7a92c
|
@ -12,13 +12,18 @@
|
|||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${apache.commons.lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -38,6 +43,7 @@
|
|||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<apache.commons.lang3.version>3.14.0</apache.commons.lang3.version>
|
||||
<guava.version>33.0.0-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.firstnchars;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.base.Ascii;
|
||||
|
||||
class FirstNCharactersUnitTest {
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingSubstringMethod_thenGetFirstChars() {
|
||||
String givenInput = "Hello Baeldung Readers";
|
||||
|
||||
assertEquals("He", givenInput.substring(0, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingSubSequenceMethod_thenGetFirstChars() {
|
||||
String givenInput = "Welcome";
|
||||
|
||||
assertEquals("Wel", givenInput.subSequence(0, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingStreamApi_thenGetFirstChars() {
|
||||
String givenInput = "The world is beautiful";
|
||||
String result = givenInput.chars()
|
||||
.limit(3)
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
|
||||
assertEquals("The", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingStringUtilsSubstringMethod_thenGetFirstChars() {
|
||||
String givenInput = "Baeldung";
|
||||
|
||||
assertEquals("Baeld", StringUtils.substring(givenInput, 0, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingStringUtilsLeftMethod_thenGetFirstChars() {
|
||||
String givenInput = "kindness always wins";
|
||||
|
||||
assertEquals("kind", StringUtils.left(givenInput, 4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingGuavaTruncateMethod_thenGetFirstChars() {
|
||||
String givenInput = "Tamassint";
|
||||
|
||||
assertEquals("Tama", Ascii.truncate(givenInput, 4, ""));
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue