[BAEL-8232] - Moved java string related code and github links into new module java-strings

This commit is contained in:
amit2103
2018-08-18 20:54:24 +05:30
parent 3a6638074f
commit ab17b8e697
51 changed files with 284 additions and 80 deletions

27
java-strings/README.md Normal file
View File

@@ -0,0 +1,27 @@
=========
## Java Strings Cookbooks and Examples
### Relevant Articles:
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)

174
java-strings/pom.xml Normal file
View File

@@ -0,0 +1,174 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>java-strings</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>java-strings</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-bytecode</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>${icu4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>java-strings</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version>
<lombok.version>1.16.12</lombok.version>
<vavr.version>0.9.0</vavr.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<joda.version>2.10</joda.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
<avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<icu4j.version>61.1</icu4j.version>
</properties>
</project>

View File

@@ -0,0 +1,11 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
public class UseLocalDateTime {
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
return LocalDateTime.parse(representation);
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.java9.compactstring;
import java.util.List;
import static java.util.stream.Collectors.toList;
import java.util.stream.IntStream;
public class CompactStringDemo {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
List strings = IntStream.rangeClosed(1, 10_000_000)
.mapToObj(Integer::toString).collect(toList());
long totalTime = System.currentTimeMillis() - startTime;
System.out.println("Generated " + strings.size() + " strings in "
+ totalTime + " ms.");
startTime = System.currentTimeMillis();
String appended = (String) strings.stream().limit(100_000)
.reduce("", (left, right) -> left.toString() + right.toString());
totalTime = System.currentTimeMillis() - startTime;
System.out.println("Created string of length " + appended.length()
+ " in " + totalTime + " ms.");
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.string;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JoinerSplitter {
public static String join ( String[] arrayOfString ) {
return Arrays.asList(arrayOfString)
.stream()
.map(x -> x)
.collect(Collectors.joining(","));
}
public static String joinWithPrefixPostFix ( String[] arrayOfString ) {
return Arrays.asList(arrayOfString)
.stream()
.map(x -> x)
.collect(Collectors.joining(",","[","]"));
}
public static List<String> split ( String str ) {
return Stream.of(str.split(","))
.map (elem -> new String(elem))
.collect(Collectors.toList());
}
public static List<Character> splitToListOfChar ( String str ) {
return str.chars()
.mapToObj(item -> (char) item)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,66 @@
package com.baeldung.string;
import java.util.stream.IntStream;
public class Palindrome {
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
public boolean isPalindromeReverseTheString(String text) {
StringBuilder reverse = new StringBuilder();
String clean = text.replaceAll("\\s+", "").toLowerCase();
char[] plain = clean.toCharArray();
for (int i = plain.length - 1; i >= 0; i--)
reverse.append(plain[i]);
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeUsingStringBuilder(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
StringBuilder plain = new StringBuilder(clean);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeUsingStringBuffer(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
StringBuffer plain = new StringBuffer(clean);
StringBuffer reverse = plain.reverse();
return (reverse.toString()).equals(clean);
}
public boolean isPalindromeRecursive(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
return recursivePalindrome(clean, 0, clean.length() - 1);
}
private boolean recursivePalindrome(String text, int forward, int backward) {
if (forward == backward)
return true;
if ((text.charAt(forward)) != (text.charAt(backward)))
return false;
if (forward < backward + 1) {
return recursivePalindrome(text, forward + 1, backward - 1);
}
return true;
}
public boolean isPalindromeUsingIntStream(String text) {
String temp = text.replaceAll("\\s+", "").toLowerCase();
return IntStream.range(0, temp.length() / 2)
.noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.string;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class StringBufferStringBuilder {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(StringBufferStringBuilder.class.getSimpleName())
.build();
new Runner(opt).run();
}
@State(Scope.Benchmark)
public static class MyState {
int iterations = 1000;
String initial = "abc";
String suffix = "def";
}
@Benchmark
public StringBuffer benchmarkStringBuffer(MyState state) {
StringBuffer stringBuffer = new StringBuffer(state.initial);
for (int i = 0; i < state.iterations; i++) {
stringBuffer.append(state.suffix);
}
return stringBuffer;
}
@Benchmark
public StringBuilder benchmarkStringBuilder(MyState state) {
StringBuilder stringBuilder = new StringBuilder(state.initial);
for (int i = 0; i < state.iterations; i++) {
stringBuilder.append(state.suffix);
}
return stringBuilder;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.string;
import java.util.Optional;
class StringHelper {
static String removeLastChar(String s) {
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
}
static String removeLastCharRegex(String s) {
return (s == null) ? s : s.replaceAll(".$", "");
}
static String removeLastCharOptional(String s) {
return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s);
}
static String removeLastCharRegexOptional(String s) {
return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s);
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.string;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.commons.lang3.text.WordUtils;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
public class TitleCaseConverter {
private static final String WORD_SEPARATOR = " ";
public static String convertToTitleCaseIteratingChars(String text) {
if (text == null || text.isEmpty()) {
return text;
}
StringBuilder converted = new StringBuilder();
boolean convertNext = true;
for (char ch : text.toCharArray()) {
if (Character.isSpaceChar(ch)) {
convertNext = true;
} else if (convertNext) {
ch = Character.toTitleCase(ch);
convertNext = false;
} else {
ch = Character.toLowerCase(ch);
}
converted.append(ch);
}
return converted.toString();
}
public static String convertToTitleCaseSplitting(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return Arrays
.stream(text.split(WORD_SEPARATOR))
.map(word -> word.isEmpty()
? word
: Character.toTitleCase(word.charAt(0)) + word
.substring(1)
.toLowerCase())
.collect(Collectors.joining(WORD_SEPARATOR));
}
public static String convertToTitleCaseIcu4j(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return UCharacter.toTitleCase(text, BreakIterator.getTitleInstance());
}
public static String convertToTileCaseWordUtilsFull(String text) {
return WordUtils.capitalizeFully(text);
}
public static String convertToTileCaseWordUtils(String text) {
return WordUtils.capitalize(text);
}
}

View File

@@ -0,0 +1,75 @@
package com.baeldung.stringisnumeric;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class Benchmarking {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(Benchmarking.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
@State(Scope.Thread)
public static class ExecutionPlan {
public String number = Integer.toString(Integer.MAX_VALUE);
public boolean isNumber = false;
public IsNumeric isNumeric= new IsNumeric();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingCoreJava(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingRegularExpressions(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
public class IsNumeric {
public boolean usingCoreJava(String strNum) {
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
public boolean usingRegularExpressions(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?");
}
public boolean usingNumberUtils_isCreatable(String strNum) {
return NumberUtils.isCreatable(strNum);
}
public boolean usingNumberUtils_isParsable(String strNum) {
return NumberUtils.isParsable(strNum);
}
public boolean usingStringUtils_isNumeric(String strNum) {
return StringUtils.isNumeric(strNum);
}
public boolean usingStringUtils_isNumericSpace(String strNum) {
return StringUtils.isNumericSpace(strNum);
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.stringisnumeric;
import org.apache.log4j.Logger;
public class IsNumericDriver {
private static IsNumeric isNumeric;
private static Logger LOG = Logger.getLogger(IsNumericDriver.class);
static {
isNumeric =new IsNumeric();
}
public static void main(String[] args) {
LOG.info("Testing all methods...");
boolean res = isNumeric.usingCoreJava("1001");
LOG.info("Using Core Java : " + res);
res = isNumeric.usingRegularExpressions("1001");
LOG.info("Using Regular Expressions : " + res);
res =isNumeric.usingNumberUtils_isCreatable("1001");
LOG.info("Using NumberUtils.isCreatable : " + res);
res =isNumeric.usingNumberUtils_isParsable("1001");
LOG.info("Using NumberUtils.isParsable : " + res);
res =isNumeric.usingStringUtils_isNumeric("1001");
LOG.info("Using StringUtils.isNumeric : " + res);
res =isNumeric.usingStringUtils_isNumericSpace("1001");
LOG.info("Using StringUtils.isNumericSpace : " + res);
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.stringtokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class MyTokenizer {
public List<String> getTokens(String str) {
List<String> tokens = new ArrayList<>();
// StringTokenizer tokenizer = new StringTokenizer( str );
StringTokenizer tokenizer = new StringTokenizer(str, ",");
// StringTokenizer tokenizer = new StringTokenizer( str , "," , true );
while (tokenizer.hasMoreElements()) {
tokens.add(tokenizer.nextToken());
// tokens.add( tokenizer.nextToken("e") );
}
int tokenLength = tokens.size();
return tokens;
}
public List<String> getTokensWithCollection(String str) {
return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList());
}
public List<String> getTokensFromFile(String path, String delim) {
List<String> tokens = new ArrayList<>();
String currLine;
StringTokenizer tokenizer;
try (BufferedReader br = new BufferedReader(new InputStreamReader(MyTokenizer.class.getResourceAsStream("/" + path)))) {
while ((currLine = br.readLine()) != null) {
tokenizer = new StringTokenizer(currLine, delim);
while (tokenizer.hasMoreElements()) {
tokens.add(tokenizer.nextToken());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return tokens;
}
}

View File

@@ -0,0 +1,3 @@
1|IND|India
2|MY|Malaysia
3|AU|Australia
1 1 IND India
2 2 MY Malaysia
3 3 AU Australia

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,62 @@
package com.baeldung;
import static org.junit.Assert.*;
import org.junit.Test;
public class CharArrayToStringUnitTest {
@Test
public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = new String(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = new String(charArray, 4, 3);
String expectedValue = "act";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.copyValueOf(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.copyValueOf(charArray, 0, 4);
String expectedValue = "char";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.valueOf(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.valueOf(charArray, 3, 4);
String expectedValue = "ract";
assertEquals(expectedValue, result);
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CharToStringUnitTest {
@Test
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
final char givenChar = 'x';
final String result = String.valueOf(givenChar);
assertThat(result).isEqualTo("x");
}
@Test
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() {
final char givenChar = 'x';
final String result = Character.toString(givenChar);
assertThat(result).isEqualTo("x");
}
@Test
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3() {
final char givenChar = 'x';
final String result = new Character(givenChar).toString();
assertThat(result).isEqualTo("x");
}
@Test
public void givenChar_whenConcatenated_shouldConvertToString4() {
final char givenChar = 'x';
final String result = givenChar + "";
assertThat(result).isEqualTo("x");
}
@Test
public void givenChar_whenFormated_shouldConvertToString5() {
final char givenChar = 'x';
final String result = String.format("%c", givenChar);
assertThat(result).isEqualTo("x");
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung;
import static org.junit.Assert.*;
import org.junit.Test;
public class StringToCharArrayUnitTest {
@Test
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
String givenString = "characters";
char[] result = givenString.toCharArray();
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
assertArrayEquals(expectedCharArray, result);
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import com.google.common.primitives.Ints;
public class StringToIntOrIntegerUnitTest {
@Test
public void givenString_whenParsingInt_shouldConvertToInt() {
String givenString = "42";
int result = Integer.parseInt(givenString);
assertThat(result).isEqualTo(42);
}
@Test
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
String givenString = "42";
Integer result = Integer.valueOf(givenString);
assertThat(result).isEqualTo(new Integer(42));
}
@Test
public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() {
String givenString = "42";
Integer result = new Integer(givenString);
assertThat(result).isEqualTo(new Integer(42));
}
@Test
public void givenString_whenCallingIntegerDecode_shouldConvertToInt() {
String givenString = "42";
int result = Integer.decode(givenString);
assertThat(result).isEqualTo(42);
}
@Test
public void givenString_whenTryParse_shouldConvertToInt() {
String givenString = "42";
Integer result = Ints.tryParse(givenString);
assertThat(result).isEqualTo(42);
}
@Test(expected = NumberFormatException.class)
public void givenInvalidInput_whenParsingInt_shouldThrow() {
String givenString = "nan";
Integer.parseInt(givenString);
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.chararraypassword;
import org.junit.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class PasswordStoreExamplesUnitTest {
String stringPassword = "password";
char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
@Test
public void givenStringHashCode_WhenStringValueChanged_ThenHashCodesNotEqualAndValesNotEqual() {
String originalHashCode = Integer.toHexString(stringPassword.hashCode());
stringPassword = "********";
String changedHashCode = Integer.toHexString(stringPassword.hashCode());
assertThat(originalHashCode).isNotEqualTo(changedHashCode);
assertThat(stringPassword).isNotEqualTo("password");
}
@Test
public void givenStringHashCode_WhenStringValueChangedAndStringValueReassigned_ThenHashCodesEqualAndValesEqual() {
String originalHashCode = Integer.toHexString(stringPassword.hashCode());
stringPassword = "********";
stringPassword = "password";
String reassignedHashCode = Integer.toHexString(stringPassword.hashCode());
assertThat(originalHashCode).isEqualTo(reassignedHashCode);
assertThat(stringPassword).isEqualTo("password");
}
@Test
public void givenStringHashCode_WhenStringValueReplaced_ThenHashCodesEqualAndValesEqual() {
String originalHashCode = Integer.toHexString(stringPassword.hashCode());
String newString = "********";
stringPassword.replace(stringPassword, newString);
String hashCodeAfterReplace = Integer.toHexString(stringPassword.hashCode());
assertThat(originalHashCode).isEqualTo(hashCodeAfterReplace);
assertThat(stringPassword).isEqualTo("password");
}
@Test
public void givenCharArrayHashCode_WhenArrayElementsValueChanged_ThenHashCodesEqualAndValesNotEqual() {
String originalHashCode = Integer.toHexString(charPassword.hashCode());
Arrays.fill(charPassword, '*');
String changedHashCode = Integer.toHexString(charPassword.hashCode());
assertThat(originalHashCode).isEqualTo(changedHashCode);
assertThat(charPassword).isNotEqualTo(new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'});
}
@Test
public void whenCallingToStringOfString_ThenValuesEqual() {
assertThat(stringPassword.toString()).isEqualTo("password");
}
@Test
public void whenCallingToStringOfCharArray_ThenValuesNotEqual() {
assertThat(charPassword.toString()).isNotEqualTo("password");
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.fileToBase64StringConversion;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
public class FileToBase64StringConversionUnitTest {
private String inputFilePath = "test_image.jpg";
private String outputFilePath = "test_image_copy.jpg";
@Test
public void fileToBase64StringConversion() throws IOException {
//load file from /src/test/resources
ClassLoader classLoader = getClass().getClassLoader();
File inputFile = new File(classLoader
.getResource(inputFilePath)
.getFile());
byte[] fileContent = FileUtils.readFileToByteArray(inputFile);
String encodedString = Base64
.getEncoder()
.encodeToString(fileContent);
//create output file
File outputFile = new File(inputFile
.getParentFile()
.getAbsolutePath() + File.pathSeparator + outputFilePath);
// decode the string and write to file
byte[] decodedBytes = Base64
.getDecoder()
.decode(encodedString);
FileUtils.writeByteArrayToFile(outputFile, decodedBytes);
assertTrue(FileUtils.contentEquals(inputFile, outputFile));
}
}

View File

@@ -0,0 +1,2 @@
Relevant Articles:
- [Java String Conversions](http://www.baeldung.com/java-string-conversions)

View File

@@ -0,0 +1,128 @@
package com.baeldung.java.conversion;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.junit.Test;
import com.baeldung.datetime.UseLocalDateTime;
public class StringConversionUnitTest {
@Test
public void whenConvertedToInt_thenCorrect() {
String beforeConvStr = "1";
int afterConvInt = 1;
assertEquals(Integer.parseInt(beforeConvStr), afterConvInt);
}
@Test
public void whenConvertedToInteger_thenCorrect() {
String beforeConvStr = "12";
Integer afterConvInteger = 12;
assertEquals(Integer.valueOf(beforeConvStr).equals(afterConvInteger), true);
}
@Test
public void whenConvertedTolong_thenCorrect() {
String beforeConvStr = "12345";
long afterConvLongPrimitive = 12345;
assertEquals(Long.parseLong(beforeConvStr), afterConvLongPrimitive);
}
@Test
public void whenConvertedToLong_thenCorrect() {
String beforeConvStr = "14567";
Long afterConvLong = 14567l;
assertEquals(Long.valueOf(beforeConvStr).equals(afterConvLong), true);
}
@Test
public void whenConvertedTodouble_thenCorrect() {
String beforeConvStr = "1.4";
double afterConvDoublePrimitive = 1.4;
assertEquals(Double.parseDouble(beforeConvStr), afterConvDoublePrimitive, 0.0);
}
@Test
public void whenConvertedToDouble_thenCorrect() {
String beforeConvStr = "145.67";
double afterConvDouble = 145.67d;
assertEquals(Double.valueOf(beforeConvStr).equals(afterConvDouble), true);
}
@Test
public void whenConvertedToByteArr_thenCorrect() {
String beforeConvStr = "abc";
byte[] afterConvByteArr = new byte[] { 'a', 'b', 'c' };
assertEquals(Arrays.equals(beforeConvStr.getBytes(), afterConvByteArr), true);
}
@Test
public void whenConvertedToboolean_thenCorrect() {
String beforeConvStr = "true";
boolean afterConvBooleanPrimitive = true;
assertEquals(Boolean.parseBoolean(beforeConvStr), afterConvBooleanPrimitive);
}
@Test
public void whenConvertedToBoolean_thenCorrect() {
String beforeConvStr = "true";
Boolean afterConvBoolean = true;
assertEquals(Boolean.valueOf(beforeConvStr), afterConvBoolean);
}
@Test
public void whenConvertedToCharArr_thenCorrect() {
String beforeConvStr = "hello";
char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' };
assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true);
}
@Test
public void whenConvertedToDate_thenCorrect() throws ParseException {
String beforeConvStr = "15/10/2013";
int afterConvCalendarDay = 15;
int afterConvCalendarMonth = 9;
int afterConvCalendarYear = 2013;
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy");
Date afterConvDate = formatter.parse(beforeConvStr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(afterConvDate);
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), afterConvCalendarDay);
assertEquals(calendar.get(Calendar.MONTH), afterConvCalendarMonth);
assertEquals(calendar.get(Calendar.YEAR), afterConvCalendarYear);
}
@Test
public void whenConvertedToLocalDateTime_thenCorrect() {
String str = "2007-12-03T10:15:30";
int afterConvCalendarDay = 03;
Month afterConvCalendarMonth = Month.DECEMBER;
int afterConvCalendarYear = 2007;
LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
assertEquals(afterConvDate.getYear(), afterConvCalendarYear);
}
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.java8.base64;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.*;
public class ApacheCommonsEncodeDecodeUnitTest {
// tests
@Test
public void whenStringIsEncoded() throws UnsupportedEncodingException {
final String originalInput = "test input";
final Base64 base64 = new Base64();
final String encodedString = new String(base64.encode(originalInput.getBytes()));
assertNotNull(encodedString);
assertNotEquals(originalInput, encodedString);
}
@Test
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
final String originalInput = "test input";
final Base64 base64 = new Base64();
final String encodedString = new String(base64.encode(originalInput.getBytes()));
final String decodedString = new String(base64.decode(encodedString.getBytes()));
assertNotNull(decodedString);
assertEquals(originalInput, decodedString);
}
@Test
public void whenStringIsEncodedUsingStaticMethod() throws UnsupportedEncodingException {
final String originalInput = "test input";
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
assertNotNull(encodedString);
assertNotEquals(originalInput, encodedString);
}
@Test
public void whenStringIsEncodedUsingStaticMethod_thenStringCanBeDecodedUsingStaticMethod() throws UnsupportedEncodingException {
final String originalInput = "test input";
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
final String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));
assertNotNull(decodedString);
assertEquals(originalInput, decodedString);
}
}

View File

@@ -0,0 +1,109 @@
package com.baeldung.java8.base64;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;
import static org.junit.Assert.*;
public class Java8EncodeDecodeUnitTest {
// tests
@Test
public void whenStringIsEncoded_thenOk() throws UnsupportedEncodingException {
final String originalInput = "test input";
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
assertNotNull(encodedString);
assertNotEquals(originalInput, encodedString);
}
@Test
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
final String originalInput = "test input";
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
final String decodedString = new String(decodedBytes);
assertNotNull(decodedString);
assertEquals(originalInput, decodedString);
}
@Test
public void whenStringIsEncodedWithoutPadding_thenOk() throws UnsupportedEncodingException {
final String originalInput = "test input";
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
assertNotNull(encodedString);
assertNotEquals(originalInput, encodedString);
}
@Test
public void whenStringIsEncodedWithoutPadding_thenStringCanBeDecoded() throws UnsupportedEncodingException {
final String originalInput = "test input";
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
final String decodedString = new String(decodedBytes);
assertNotNull(decodedString);
assertEquals(originalInput, decodedString);
}
@Test
public void whenUrlIsEncoded_thenOk() throws UnsupportedEncodingException {
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
assertNotNull(encodedUrl);
assertNotEquals(originalUrl, encodedUrl);
}
@Test
public void whenUrlIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException {
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
final byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl.getBytes());
final String decodedUrl = new String(decodedBytes);
assertNotNull(decodedUrl);
assertEquals(originalUrl, decodedUrl);
}
@Test
public void whenMimeIsEncoded_thenOk() throws UnsupportedEncodingException {
final StringBuilder buffer = getMimeBuffer();
final byte[] forEncode = buffer.toString().getBytes();
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
assertNotNull(encodedMime);
}
@Test
public void whenMimeIsEncoded_thenItCanBeDecoded() throws UnsupportedEncodingException {
final StringBuilder buffer = getMimeBuffer();
final byte[] forEncode = buffer.toString().getBytes();
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
final byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime);
final String decodedMime = new String(decodedBytes);
assertNotNull(decodedMime);
}
//
private static StringBuilder getMimeBuffer() {
final StringBuilder buffer = new StringBuilder();
for (int count = 0; count < 10; ++count) {
buffer.append(UUID.randomUUID().toString());
}
return buffer;
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.string;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class CharSequenceVsStringUnitTest {
@Test
public void givenUsingString_whenInstantiatingString_thenWrong() {
CharSequence firstString = "bealdung";
String secondString = "baeldung";
assertNotEquals(firstString, secondString);
}
@Test
public void givenIdenticalCharSequences_whenCastToString_thenEqual() {
CharSequence charSequence1 = "baeldung_1";
CharSequence charSequence2 = "baeldung_2";
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0);
}
@Test
public void givenString_whenAppended_thenUnmodified() {
String test = "a";
int firstAddressOfTest = System.identityHashCode(test);
test += "b";
int secondAddressOfTest = System.identityHashCode(test);
assertNotEquals(firstAddressOfTest, secondAddressOfTest);
}
@Test
public void givenStringBuilder_whenAppended_thenModified() {
StringBuilder test = new StringBuilder();
test.append("a");
int firstAddressOfTest = System.identityHashCode(test);
test.append("b");
int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest);
}
}

View File

@@ -0,0 +1,66 @@
package com.baeldung.string;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class JoinerSplitterUnitTest {
@Test
public void provided_array_convert_to_stream_and_convert_to_string() {
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
String expectation = "java,python,nodejs,ruby";
String result = JoinerSplitter.join(programming_languages);
assertEquals(result, expectation);
}
@Test
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
String[] programming_languages = {"java", "python",
"nodejs", "ruby"};
String expectation = "[java,python,nodejs,ruby]";
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
assertEquals(result, expectation);
}
@Test
public void givenString_transformedToStream_convertToList() {
String programming_languages = "java,python,nodejs,ruby";
List<String> expectation = new ArrayList<String>();
expectation.add("java");
expectation.add("python");
expectation.add("nodejs");
expectation.add("ruby");
List<String> result = JoinerSplitter.split(programming_languages);
assertEquals(result, expectation);
}
@Test
public void givenString_transformedToStream_convertToListOfChar() {
String programming_languages = "java,python,nodejs,ruby";
List<Character> expectation = new ArrayList<Character>();
char[] charArray = programming_languages.toCharArray();
for (char c : charArray) {
expectation.add(c);
}
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
assertEquals(result, expectation);
}
}

View File

@@ -0,0 +1,97 @@
package com.baeldung.string;
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeUnitTest {
private String[] words = {
"Anna",
"Civic",
"Kayak",
"Level",
"Madam",
};
private String[] sentences = {
"Sore was I ere I saw Eros",
"Euston saw I was not Sue",
"Too hot to hoot",
"No mists or frost Simon",
"Stella won no wallets"
};
private Palindrome palindrome = new Palindrome();
@Test
public void whenWord_shouldBePalindrome() {
for (String word : words)
assertTrue(palindrome.isPalindrome(word));
}
@Test
public void whenSentence_shouldBePalindrome() {
for (String sentence : sentences)
assertTrue(palindrome.isPalindrome(sentence));
}
@Test
public void whenReverseWord_shouldBePalindrome() {
for (String word : words)
assertTrue(palindrome.isPalindromeReverseTheString(word));
}
@Test
public void whenReverseSentence_shouldBePalindrome() {
for (String sentence : sentences)
assertTrue(palindrome.isPalindromeReverseTheString(sentence));
}
@Test
public void whenStringBuilderWord_shouldBePalindrome() {
for (String word : words)
assertTrue(palindrome.isPalindromeUsingStringBuilder(word));
}
@Test
public void whenStringBuilderSentence_shouldBePalindrome() {
for (String sentence : sentences)
assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence));
}
@Test
public void whenStringBufferWord_shouldBePalindrome() {
for (String word : words)
assertTrue(palindrome.isPalindromeUsingStringBuffer(word));
}
@Test
public void whenStringBufferSentence_shouldBePalindrome() {
for (String sentence : sentences)
assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence));
}
@Test
public void whenPalindromeRecursive_wordShouldBePalindrome() {
for (String word : words)
assertTrue(palindrome.isPalindromeRecursive(word));
}
@Test
public void whenPalindromeRecursive_sentenceShouldBePalindrome() {
for (String sentence : sentences)
assertTrue(palindrome.isPalindromeRecursive(sentence));
}
@Test
public void whenPalindromeStreams_wordShouldBePalindrome() {
for (String word : words)
assertTrue(palindrome.isPalindromeUsingIntStream(word));
}
@Test
public void whenPalindromeStreams_sentenceShouldBePalindrome() {
for (String sentence : sentences)
assertTrue(palindrome.isPalindromeUsingIntStream(sentence));
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.string;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.base.Splitter;
public class SplitUnitTest {
@Test
public void givenString_whenSplit_thenReturnsArray_through_JavaLangString() {
assertThat("peter,james,thomas".split(","))
.containsExactly("peter", "james", "thomas");
assertThat("car jeep scooter".split(" "))
.containsExactly("car", "jeep", "scooter");
assertThat("1-120-232323".split("-"))
.containsExactly("1", "120", "232323");
assertThat("192.168.1.178".split("\\."))
.containsExactly("192", "168", "1", "178");
assertThat("b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*"))
.containsExactly("b", "a", "e", "l", "d", "u", "n", "g");
}
@Test
public void givenString_whenSplit_thenReturnsArray_through_StringUtils() {
StringUtils.split("car jeep scooter");
assertThat(StringUtils.split("car jeep scooter"))
.containsExactly("car", "jeep", "scooter");
assertThat(StringUtils.split("car jeep scooter"))
.containsExactly("car", "jeep", "scooter");
assertThat(StringUtils.split("car:jeep:scooter", ":"))
.containsExactly("car", "jeep", "scooter");
assertThat(StringUtils.split("car.jeep.scooter", "."))
.containsExactly("car", "jeep", "scooter");
}
@Test
public void givenString_whenSplit_thenReturnsList_Splitter() {
//given
List<String> resultList = Splitter.on(',').trimResults().omitEmptyStrings().splitToList("car,jeep,, scooter");
assertThat(resultList)
.containsExactly("car", "jeep", "scooter");
}
}

View File

@@ -0,0 +1,154 @@
package com.baeldung.string;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
public class StringComparisonUnitTest {
@Test
public void whenUsingComparisonOperator_ThenComparingStrings(){
String string1 = "using comparison operator";
String string2 = "using comparison operator";
String string3 = new String("using comparison operator");
assertThat(string1 == string2).isTrue();
assertThat(string1 == string3).isFalse();
}
@Test
public void whenUsingEqualsMethod_ThenComparingStrings(){
String string1 = "using equals method";
String string2 = "using equals method";
String string3 = "using EQUALS method";
String string4 = new String("using equals method");
assertThat(string1.equals(string2)).isTrue();
assertThat(string1.equals(string4)).isTrue();
assertThat(string1.equals(null)).isFalse();
assertThat(string1.equals(string3)).isFalse();
}
@Test
public void whenUsingEqualsIgnoreCase_ThenComparingStrings(){
String string1 = "using equals ignore case";
String string2 = "USING EQUALS IGNORE CASE";
assertThat(string1.equalsIgnoreCase(string2)).isTrue();
}
@Test
public void whenUsingCompareTo_ThenComparingStrings(){
String author = "author";
String book = "book";
String duplicateBook = "book";
assertThat(author.compareTo(book)).isEqualTo(-1);
assertThat(book.compareTo(author)).isEqualTo(1);
assertThat(duplicateBook.compareTo(book)).isEqualTo(0);
}
@Test
public void whenUsingCompareToIgnoreCase_ThenComparingStrings(){
String author = "Author";
String book = "book";
String duplicateBook = "BOOK";
assertThat(author.compareToIgnoreCase(book)).isEqualTo(-1);
assertThat(book.compareToIgnoreCase(author)).isEqualTo(1);
assertThat(duplicateBook.compareToIgnoreCase(book)).isEqualTo(0);
}
@Test
public void whenUsingObjectsEqualsMethod_ThenComparingStrings(){
String string1 = "using objects equals";
String string2 = "using objects equals";
String string3 = new String("using objects equals");
assertThat(Objects.equals(string1, string2)).isTrue();
assertThat(Objects.equals(string1, string3)).isTrue();
assertThat(Objects.equals(null, null)).isTrue();
assertThat(Objects.equals(null, string1)).isFalse();
}
@Test
public void whenUsingEqualsOfApacheCommons_ThenComparingStrings(){
assertThat(StringUtils.equals(null, null)).isTrue();
assertThat(StringUtils.equals(null, "equals method")).isFalse();
assertThat(StringUtils.equals("equals method", "equals method")).isTrue();
assertThat(StringUtils.equals("equals method", "EQUALS METHOD")).isFalse();
}
@Test
public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings(){
assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue();
assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse();
assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method")).isTrue();
assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD")).isTrue();
}
@Test
public void whenUsingEqualsAnyOf_ThenComparingStrings(){
assertThat(StringUtils.equalsAny(null, null, null)).isTrue();
assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue();
assertThat(StringUtils.equalsAny("equals any", null, "equals any")).isTrue();
assertThat(StringUtils.equalsAny(null, "equals", "any")).isFalse();
assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY")).isFalse();
}
@Test
public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings(){
assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue();
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue();
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue();
assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse();
assertThat(StringUtils.equalsAnyIgnoreCase(
"equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue();
}
@Test
public void whenUsingCompare_thenComparingStringsWithNulls(){
assertThat(StringUtils.compare(null, null)).isEqualTo(0);
assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1);
assertThat(StringUtils.compare("abc", "bbc")).isEqualTo(-1);
assertThat(StringUtils.compare("bbc", "abc")).isEqualTo(1);
assertThat(StringUtils.compare("abc", "abc")).isEqualTo(0);
}
@Test
public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls(){
assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0);
assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1);
assertThat(StringUtils.compareIgnoreCase("Abc", "bbc")).isEqualTo(-1);
assertThat(StringUtils.compareIgnoreCase("bbc", "ABC")).isEqualTo(1);
assertThat(StringUtils.compareIgnoreCase("abc", "ABC")).isEqualTo(0);
}
@Test
public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings(){
assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1);
assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1);
}
}

View File

@@ -0,0 +1,93 @@
package com.baeldung.string;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class StringHelperUnitTest {
public static final String TEST_STRING = "abcdef";
public static final String NULL_STRING = null;
public static final String EMPTY_STRING = "";
public static final String ONE_CHAR_STRING = "a";
public static final String WHITE_SPACE_AT_THE_END_STRING = "abc ";
public static final String NEW_LINE_AT_THE_END_STRING = "abc\n";
public static final String MULTIPLE_LINES_STRING = "abc\ndef";
@Test
public void givenTestString_whenSubstring_thenGetStingWithoutLastChar() {
assertEquals("abcde", StringHelper.removeLastChar(TEST_STRING));
assertEquals("abcde", StringUtils.substring(TEST_STRING, 0, TEST_STRING.length() - 1));
assertEquals("abcde", StringUtils.chop(TEST_STRING));
assertEquals("abcde", TEST_STRING.replaceAll(".$", ""));
assertEquals("abcde", StringHelper.removeLastCharRegex(TEST_STRING));
assertEquals("abcde", StringHelper.removeLastCharOptional(TEST_STRING));
assertEquals("abcde", StringHelper.removeLastCharRegexOptional(TEST_STRING));
}
@Test
public void givenNullString_whenSubstring_thenGetNullString() {
assertEquals(NULL_STRING, StringHelper.removeLastChar(NULL_STRING));
assertEquals(NULL_STRING, StringUtils.chop(NULL_STRING));
assertEquals(NULL_STRING, StringHelper.removeLastCharRegex(NULL_STRING));
assertEquals(NULL_STRING, StringHelper.removeLastCharOptional(NULL_STRING));
assertEquals(NULL_STRING, StringHelper.removeLastCharRegexOptional(NULL_STRING));
}
@Test
public void givenEmptyString_whenSubstring_thenGetEmptyString() {
assertEquals(EMPTY_STRING, StringHelper.removeLastChar(EMPTY_STRING));
assertEquals(EMPTY_STRING, StringUtils.substring(EMPTY_STRING, 0, EMPTY_STRING.length() - 1));
assertEquals(EMPTY_STRING, StringUtils.chop(EMPTY_STRING));
assertEquals(EMPTY_STRING, EMPTY_STRING.replaceAll(".$", ""));
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegex(EMPTY_STRING));
assertEquals(EMPTY_STRING, StringHelper.removeLastCharOptional(EMPTY_STRING));
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegexOptional(EMPTY_STRING));
}
@Test
public void givenOneCharString_whenSubstring_thenGetEmptyString() {
assertEquals(EMPTY_STRING, StringHelper.removeLastChar(ONE_CHAR_STRING));
assertEquals(EMPTY_STRING, StringUtils.substring(ONE_CHAR_STRING, 0, ONE_CHAR_STRING.length() - 1));
assertEquals(EMPTY_STRING, StringUtils.chop(ONE_CHAR_STRING));
assertEquals(EMPTY_STRING, ONE_CHAR_STRING.replaceAll(".$", ""));
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegex(ONE_CHAR_STRING));
assertEquals(EMPTY_STRING, StringHelper.removeLastCharOptional(ONE_CHAR_STRING));
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegexOptional(ONE_CHAR_STRING));
}
@Test
public void givenStringWithWhiteSpaceAtTheEnd_whenSubstring_thenGetStringWithoutWhiteSpaceAtTheEnd() {
assertEquals("abc", StringHelper.removeLastChar(WHITE_SPACE_AT_THE_END_STRING));
assertEquals("abc", StringUtils.substring(WHITE_SPACE_AT_THE_END_STRING, 0, WHITE_SPACE_AT_THE_END_STRING.length() - 1));
assertEquals("abc", StringUtils.chop(WHITE_SPACE_AT_THE_END_STRING));
assertEquals("abc", WHITE_SPACE_AT_THE_END_STRING.replaceAll(".$", ""));
assertEquals("abc", StringHelper.removeLastCharRegex(WHITE_SPACE_AT_THE_END_STRING));
assertEquals("abc", StringHelper.removeLastCharOptional(WHITE_SPACE_AT_THE_END_STRING));
assertEquals("abc", StringHelper.removeLastCharRegexOptional(WHITE_SPACE_AT_THE_END_STRING));
}
@Test
public void givenStringWithNewLineAtTheEnd_whenSubstring_thenGetStringWithoutNewLine() {
assertEquals("abc", StringHelper.removeLastChar(NEW_LINE_AT_THE_END_STRING));
assertEquals("abc", StringUtils.substring(NEW_LINE_AT_THE_END_STRING, 0, NEW_LINE_AT_THE_END_STRING.length() - 1));
assertEquals("abc", StringUtils.chop(NEW_LINE_AT_THE_END_STRING));
assertNotEquals("abc", NEW_LINE_AT_THE_END_STRING.replaceAll(".$", ""));
assertNotEquals("abc", StringHelper.removeLastCharRegex(NEW_LINE_AT_THE_END_STRING));
assertEquals("abc", StringHelper.removeLastCharOptional(NEW_LINE_AT_THE_END_STRING));
assertNotEquals("abc", StringHelper.removeLastCharRegexOptional(NEW_LINE_AT_THE_END_STRING));
}
@Test
public void givenMultiLineString_whenSubstring_thenGetStringWithoutNewLine() {
assertEquals("abc\nde", StringHelper.removeLastChar(MULTIPLE_LINES_STRING));
assertEquals("abc\nde", StringUtils.substring(MULTIPLE_LINES_STRING, 0, MULTIPLE_LINES_STRING.length() - 1));
assertEquals("abc\nde", StringUtils.chop(MULTIPLE_LINES_STRING));
assertEquals("abc\nde", MULTIPLE_LINES_STRING.replaceAll(".$", ""));
assertEquals("abc\nde", StringHelper.removeLastCharRegex(MULTIPLE_LINES_STRING));
assertEquals("abc\nde", StringHelper.removeLastCharOptional(MULTIPLE_LINES_STRING));
assertEquals("abc\nde", StringHelper.removeLastCharRegexOptional(MULTIPLE_LINES_STRING));
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.string;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class StringToCharStreamUnitTest {
private String testString = "Tests";
@Test
public void givenTestString_whenChars_thenReturnIntStream() {
assertThat(testString.chars(), instanceOf(IntStream.class));
}
@Test
public void givenTestString_whenCodePoints_thenReturnIntStream() {
assertThat(testString.codePoints(), instanceOf(IntStream.class));
}
@Test
public void givenTestString_whenCodePoints_thenShowOccurences() throws Exception {
Map<Character, Integer> map = testString.codePoints()
.mapToObj(c -> (char) c)
.filter(Character::isLetter)
.collect(Collectors.toMap(c -> c, c -> 1, Integer::sum));
System.out.println(map);
}
@Test
public void givenIntStream_whenMapToObj_thenReturnCharacterStream() {
Stream<Character> characterStream = testString.chars()
.mapToObj(c -> (char) c);
Stream<Character> characterStream1 = testString.codePoints()
.mapToObj(c -> (char) c);
assertNotNull("IntStream returned by chars() did not map to Stream<Character>", characterStream);
assertNotNull("IntStream returned by codePoints() did not map to Stream<Character>", characterStream1);
}
@Test
public void givenIntStream_whenMapToObj_thenReturnStringStream() {
List<String> strings = testString.codePoints()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.toList());
assertEquals(strings.size(), 5);
}
}

View File

@@ -0,0 +1,226 @@
package com.baeldung.string;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.IllegalFormatException;
import java.util.regex.PatternSyntaxException;
import org.junit.Test;
public class StringUnitTest {
@Test
public void whenCallCodePointAt_thenDecimalUnicodeReturned() {
assertEquals(97, "abcd".codePointAt(0));
}
@Test(expected = StringIndexOutOfBoundsException.class)
public void whenPassNonExistingIndex_thenExceptionThrown() {
int a = "abcd".codePointAt(4);
}
@Test
public void whenCallConcat_thenCorrect() {
assertEquals("elephant", "elep".concat("hant"));
}
@Test
public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException {
byte[] byteArray1 = "abcd".getBytes();
byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII);
byte[] byteArray3 = "ijkl".getBytes("UTF-8");
byte[] expected1 = new byte[] { 97, 98, 99, 100 };
byte[] expected2 = new byte[] { 101, 102, 103, 104 };
byte[] expected3 = new byte[] { 105, 106, 107, 108 };
assertArrayEquals(expected1, byteArray1);
assertArrayEquals(expected2, byteArray2);
assertArrayEquals(expected3, byteArray3);
}
@Test
public void whenGetBytesUsingASCII_thenCorrect() {
byte[] byteArray = "efgh".getBytes(StandardCharsets.US_ASCII);
byte[] expected = new byte[] { 101, 102, 103, 104 };
assertArrayEquals(expected, byteArray);
}
@Test
public void whenCreateStringUsingByteArray_thenCorrect() {
byte[] array = new byte[] { 97, 98, 99, 100 };
String s = new String(array);
assertEquals("abcd", s);
}
@Test
public void whenCallCharAt_thenCorrect() {
assertEquals('P', "Paul".charAt(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void whenCharAtOnNonExistingIndex_thenIndexOutOfBoundsExceptionThrown() {
char character = "Paul".charAt(4);
}
@Test
public void whenCallCodePointCount_thenCorrect() {
assertEquals(2, "abcd".codePointCount(0, 2));
}
@Test(expected = IndexOutOfBoundsException.class)
public void whenSecondIndexEqualToLengthOfString_thenIndexOutOfBoundsExceptionThrown() {
char character = "Paul".charAt(4);
}
@Test
public void whenCallContains_thenCorrect() {
String s = "abcd";
assertTrue(s.contains("abc"));
assertFalse(s.contains("cde"));
}
@Test
public void whenCallCopyValueOf_thenStringConstructed() {
char[] array = new char[] { 'a', 'b', 'c', 'd' };
assertEquals("abcd", String.copyValueOf(array));
}
@Test
public void whenCallEndsWith_thenCorrect() {
String s1 = "test";
assertTrue(s1.endsWith("t"));
}
@Test
public void whenFormat_thenCorrect() {
String value = "Baeldung";
String formatted = String.format("Welcome to %s!", value);
assertEquals("Welcome to Baeldung!", formatted);
}
@Test(expected = IllegalFormatException.class)
public void whenInvalidFormatSyntax_thenIllegalFormatExceptionThrown() {
String value = "Baeldung";
String formatted = String.format("Welcome to %x!", value);
}
@Test
public void whenCallIndexOf_thenCorrect() {
assertEquals(1, "foo".indexOf("o"));
}
@Test
public void whenCallIsEmpty_thenCorrect() {
String s1 = "";
assertTrue(s1.isEmpty());
}
@Test
public void whenCallLastIndexOf_thenCorrect() {
assertEquals(2, "foo".lastIndexOf("o"));
assertEquals(2, "foo".lastIndexOf(111));
}
@Test
public void whenCallRegionMatches_thenCorrect() {
assertTrue("welcome to baeldung".regionMatches(false, 11, "baeldung", 0, 8));
}
@Test
public void whenCallStartsWith_thenCorrect() {
assertTrue("foo".startsWith("f"));
}
@Test
public void whenTrim_thenCorrect() {
assertEquals("foo", " foo ".trim());
}
@Test
public void whenSplit_thenCorrect() {
String s = "Welcome to Baeldung";
String[] array = new String[] { "Welcome", "to", "Baeldung" };
assertArrayEquals(array, s.split(" "));
}
@Test(expected = PatternSyntaxException.class)
public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() {
String s = "Welcome*to Baeldung";
String[] result = s.split("*");
}
@Test
public void whenCallSubSequence_thenCorrect() {
String s = "Welcome to Baeldung";
assertEquals("Welcome", s.subSequence(0, 7));
}
@Test
public void whenCallSubstring_thenCorrect() {
String s = "Welcome to Baeldung";
assertEquals("Welcome", s.substring(0, 7));
}
@Test(expected = IndexOutOfBoundsException.class)
public void whenSecondIndexEqualToLengthOfString_thenCorrect() {
String s = "Welcome to Baeldung";
String sub = s.substring(0, 20);
}
@Test
public void whenConvertToUpperCase_thenCorrect() {
String s = "Welcome to Baeldung!";
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase());
}
@Test
public void whenConvertToLowerCase_thenCorrect() {
String s = "WELCOME to BAELDUNG!";
assertEquals("welcome to baeldung!", s.toLowerCase());
}
@Test
public void whenCallReplace_thenCorrect() {
String s = "I learn Spanish";
assertEquals("I learn French", s.replaceAll("Spanish", "French"));
}
@Test
public void whenIntern_thenCorrect() {
String s1 = "abc";
String s2 = new String("abc");
String s3 = new String("foo");
String s4 = s1.intern();
String s5 = s2.intern();
assertFalse(s3 == s4);
assertTrue(s1 == s5);
}
@Test
public void whenCallValueOf_thenCorrect() {
long l = 200L;
assertEquals("200", String.valueOf(l));
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.string;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class TitleCaseConverterUnitTest {
private static final String TEXT = "tHis IS a tiTLe";
private static final String TEXT_EXPECTED = "This Is A Title";
private static final String TEXT_EXPECTED_NOT_FULL = "THis IS A TiTLe";
private static final String TEXT_OTHER_DELIMITERS = "tHis, IS a tiTLe";
private static final String TEXT_EXPECTED_OTHER_DELIMITERS = "This, Is A Title";
private static final String TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL = "THis, IS A TiTLe";
@Test
public void whenConvertingToTitleCaseIterating_thenStringConverted() {
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT));
}
@Test
public void whenConvertingToTitleCaseSplitting_thenStringConverted() {
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseSplitting(TEXT));
}
@Test
public void whenConvertingToTitleCaseUsingWordUtilsFull_thenStringConverted() {
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT));
}
@Test
public void whenConvertingToTitleCaseUsingWordUtils_thenStringConvertedOnlyFirstCharacter() {
assertEquals(TEXT_EXPECTED_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT));
}
@Test
public void whenConvertingToTitleCaseUsingIcu4j_thenStringConverted() {
assertEquals(TEXT_EXPECTED, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT));
}
@Test
public void whenConvertingToTitleCaseWithDifferentDelimiters_thenDelimitersKept() {
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIteratingChars(TEXT_OTHER_DELIMITERS));
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseSplitting(TEXT_OTHER_DELIMITERS));
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTileCaseWordUtilsFull(TEXT_OTHER_DELIMITERS));
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS_NOT_FULL, TitleCaseConverter.convertToTileCaseWordUtils(TEXT_OTHER_DELIMITERS));
assertEquals(TEXT_EXPECTED_OTHER_DELIMITERS, TitleCaseConverter.convertToTitleCaseIcu4j(TEXT_OTHER_DELIMITERS));
}
@Test
public void givenNull_whenConvertingToTileCase_thenReturnNull() {
assertEquals(null, TitleCaseConverter.convertToTitleCaseIteratingChars(null));
assertEquals(null, TitleCaseConverter.convertToTitleCaseSplitting(null));
assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtilsFull(null));
assertEquals(null, TitleCaseConverter.convertToTileCaseWordUtils(null));
assertEquals(null, TitleCaseConverter.convertToTitleCaseIcu4j(null));
}
@Test
public void givenEmptyString_whenConvertingToTileCase_thenReturnEmptyString() {
assertEquals("", TitleCaseConverter.convertToTitleCaseIteratingChars(""));
assertEquals("", TitleCaseConverter.convertToTitleCaseSplitting(""));
assertEquals("", TitleCaseConverter.convertToTileCaseWordUtilsFull(""));
assertEquals("", TitleCaseConverter.convertToTileCaseWordUtils(""));
assertEquals("", TitleCaseConverter.convertToTitleCaseIcu4j(""));
}
}

View File

@@ -0,0 +1,141 @@
package com.baeldung.string.formatter;
import java.util.Calendar;
import java.util.Formatter;
import java.util.GregorianCalendar;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class StringFormatterExampleUnitTest {
@Test
public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() {
//Syntax of Format Specifiers for Date/Time Representation
Calendar c = new GregorianCalendar(2017, 11, 10);
String s = String.format("The date is: %tm %1$te,%1$tY", c);
assertEquals("The date is: 12 10,2017", s);
}
@Test
public void givenString_whenGeneralConversion_thenConvertedString() {
//General Conversions
String s = String.format("The correct answer is %s", false);
assertEquals("The correct answer is false", s);
s = String.format("The correct answer is %b", null);
assertEquals("The correct answer is false", s);
s = String.format("The correct answer is %B", true);
assertEquals("The correct answer is TRUE", s);
}
@Test
public void givenString_whenCharConversion_thenConvertedString() {
//Character Conversions
String s = String.format("The correct answer is %c", 'a');
assertEquals("The correct answer is a", s);
s = String.format("The correct answer is %c", null);
assertEquals("The correct answer is null", s);
s = String.format("The correct answer is %C", 'b');
assertEquals("The correct answer is B", s);
s = String.format("The valid unicode character: %c", 0x0400);
assertTrue(Character.isValidCodePoint(0x0400));
assertEquals("The valid unicode character: Ѐ", s);
}
@Test(expected = java.util.IllegalFormatCodePointException.class)
public void givenString_whenIllegalCodePointForConversion_thenError() {
String s = String.format("The valid unicode character: %c", 0x11FFFF);
assertFalse(Character.isValidCodePoint(0x11FFFF));
assertEquals("The valid unicode character: Ā", s);
}
@Test
public void givenString_whenNumericIntegralConversion_thenConvertedString() {
//Numeric Integral Conversions
String s = String.format("The number 25 in decimal = %d", 25);
assertEquals("The number 25 in decimal = 25", s);
s = String.format("The number 25 in octal = %o", 25);
assertEquals("The number 25 in octal = 31", s);
s = String.format("The number 25 in hexadecimal = %x", 25);
assertEquals("The number 25 in hexadecimal = 19", s);
}
@Test
public void givenString_whenNumericFloatingConversion_thenConvertedString() {
//Numeric Floating-point Conversions
String s = String.format("The computerized scientific format of 10000.00 "
+ "= %e", 10000.00);
assertEquals("The computerized scientific format of 10000.00 = 1.000000e+04", s);
s = String.format("The decimal format of 10.019 = %f", 10.019);
assertEquals("The decimal format of 10.019 = 10.019000", s);
}
@Test
public void givenString_whenLineSeparatorConversion_thenConvertedString() {
//Line Separator Conversion
String s = String.format("First Line %nSecond Line");
assertEquals("First Line " + System.getProperty("line.separator")
+ "Second Line", s);
}
@Test
public void givenString_whenSpecifyFlag_thenGotFormattedString() {
//Without left-justified flag
String s = String.format("Without left justified flag: %5d", 25);
assertEquals("Without left justified flag: 25", s);
//Using left-justified flag
s = String.format("With left justified flag: %-5d", 25);
assertEquals("With left justified flag: 25 ", s);
}
@Test
public void givenString_whenSpecifyPrecision_thenGotExpected() {
//Precision
String s = String.format("Output of 25.09878 with Precision 2: %.2f", 25.09878);
assertEquals("Output of 25.09878 with Precision 2: 25.10", s);
s = String.format("Output of general conversion type with Precision 2: %.2b", true);
assertEquals("Output of general conversion type with Precision 2: tr", s);
}
@Test
public void givenString_whenSpecifyArgumentIndex_thenGotExpected() {
Calendar c = new GregorianCalendar(2017, 11, 10);
//Argument_Index
String s = String.format("The date is: %tm %1$te,%1$tY", c);
assertEquals("The date is: 12 10,2017", s);
s = String.format("The date is: %tm %<te,%<tY", c);
assertEquals("The date is: 12 10,2017", s);
}
@Test
public void givenAppendable_whenCreateFormatter_thenFormatterWorksOnAppendable() {
//Using String Formatter with Appendable
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format("I am writting to a %s Instance.", sb.getClass());
assertEquals("I am writting to a class java.lang.StringBuilder Instance.", sb.toString());
}
@Test
public void givenString_whenNoArguments_thenExpected() {
//Using String Formatter without arguments
String s = String.format("John scored 90%% in Fall semester");
assertEquals("John scored 90% in Fall semester", s);
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class CoreJavaIsNumericUnitTest {
public static boolean isNumeric(String strNum) {
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
@Test
public void whenUsingCoreJava_thenTrue() {
// Valid Numbers
assertThat(isNumeric("22")).isTrue();
assertThat(isNumeric("5.05")).isTrue();
assertThat(isNumeric("-200")).isTrue();
assertThat(isNumeric("10.0d")).isTrue();
assertThat(isNumeric(" 22 ")).isTrue();
// Invalid Numbers
assertThat(isNumeric(null)).isFalse();
assertThat(isNumeric("")).isFalse();
assertThat(isNumeric("abc")).isFalse();
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;
public class NumberUtilsIsCreatableUnitTest {
@Test
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
// Valid Numbers
assertThat(NumberUtils.isCreatable("22")).isTrue();
assertThat(NumberUtils.isCreatable("5.05")).isTrue();
assertThat(NumberUtils.isCreatable("-200")).isTrue();
assertThat(NumberUtils.isCreatable("10.0d")).isTrue();
assertThat(NumberUtils.isCreatable("1000L")).isTrue();
assertThat(NumberUtils.isCreatable("0xFF")).isTrue();
assertThat(NumberUtils.isCreatable("07")).isTrue();
assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue();
// Invalid Numbers
assertThat(NumberUtils.isCreatable(null)).isFalse();
assertThat(NumberUtils.isCreatable("")).isFalse();
assertThat(NumberUtils.isCreatable("abc")).isFalse();
assertThat(NumberUtils.isCreatable(" 22 ")).isFalse();
assertThat(NumberUtils.isCreatable("09")).isFalse();
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;
public class NumberUtilsIsParsableUnitTest {
@Test
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
// Valid Numbers
assertThat(NumberUtils.isParsable("22")).isTrue();
assertThat(NumberUtils.isParsable("-23")).isTrue();
assertThat(NumberUtils.isParsable("2.2")).isTrue();
assertThat(NumberUtils.isParsable("09")).isTrue();
// Invalid Numbers
assertThat(NumberUtils.isParsable(null)).isFalse();
assertThat(NumberUtils.isParsable("")).isFalse();
assertThat(NumberUtils.isParsable("6.2f")).isFalse();
assertThat(NumberUtils.isParsable("9.8d")).isFalse();
assertThat(NumberUtils.isParsable("22L")).isFalse();
assertThat(NumberUtils.isParsable("0xFF")).isFalse();
assertThat(NumberUtils.isParsable("2.99e+8")).isFalse();
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class RegularExpressionsUnitTest {
public static boolean isNumeric(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?");
}
@Test
public void whenUsingRegularExpressions_thenTrue() {
// Valid Numbers
assertThat(isNumeric("22")).isTrue();
assertThat(isNumeric("5.05")).isTrue();
assertThat(isNumeric("-200")).isTrue();
// Invalid Numbers
assertThat(isNumeric("abc")).isFalse();
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StringUtilsIsNumericSpaceUnitTest {
@Test
public void givenApacheCommons_whenUsingIsNumericSpace_thenTrue() {
// Valid Numbers
assertThat(StringUtils.isNumericSpace("123")).isTrue();
assertThat(StringUtils.isNumericSpace("١٢٣")).isTrue();
assertThat(StringUtils.isNumericSpace("")).isTrue();
assertThat(StringUtils.isNumericSpace(" ")).isTrue();
assertThat(StringUtils.isNumericSpace("12 3")).isTrue();
// Invalid Numbers
assertThat(StringUtils.isNumericSpace(null)).isFalse();
assertThat(StringUtils.isNumericSpace("ab2c")).isFalse();
assertThat(StringUtils.isNumericSpace("12.3")).isFalse();
assertThat(StringUtils.isNumericSpace("-123")).isFalse();
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StringUtilsIsNumericUnitTest {
@Test
public void givenApacheCommons_whenUsingIsNumeric_thenTrue() {
// Valid Numbers
assertThat(StringUtils.isNumeric("123")).isTrue();
assertThat(StringUtils.isNumeric("١٢٣")).isTrue();
assertThat(StringUtils.isNumeric("१२३")).isTrue();
// Invalid Numbers
assertThat(StringUtils.isNumeric(null)).isFalse();
assertThat(StringUtils.isNumeric("")).isFalse();
assertThat(StringUtils.isNumeric(" ")).isFalse();
assertThat(StringUtils.isNumeric("12 3")).isFalse();
assertThat(StringUtils.isNumeric("ab2c")).isFalse();
assertThat(StringUtils.isNumeric("12.3")).isFalse();
assertThat(StringUtils.isNumeric("-123")).isFalse();
}
}

View File

@@ -0,0 +1,101 @@
package com.baeldung.stringjoiner;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import org.junit.Test;
public class StringJoinerUnitTest {
private final String DELIMITER_COMMA = ",";
private final String DELIMITER_HYPHEN = "-";
private final String PREFIX = "[";
private final String SUFFIX = "]";
private final String EMPTY_JOINER = "empty";
@Test
public void whenJoinerWithoutPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
assertEquals(0, commaSeparatedJoiner.toString().length());
}
@Test
public void whenJoinerWithPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), PREFIX + SUFFIX);
}
@Test
public void whenJoinerWithoutPrefixSuffixWithEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
commaSeparatedJoiner.setEmptyValue(EMPTY_JOINER);
assertEquals(commaSeparatedJoiner.toString(), EMPTY_JOINER);
}
@Test
public void whenJoinerWithPrefixSuffixWithEmptyValue_thenReturnDefault() {
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
commaSeparatedPrefixSuffixJoiner.setEmptyValue(EMPTY_JOINER);
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), EMPTY_JOINER);
}
@Test
public void whenAddElements_thenJoinElements() {
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
rgbJoiner.add("Red")
.add("Green")
.add("Blue");
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}
@Test
public void whenAddListElements_thenJoinListElements() {
List<String> rgbList = new ArrayList<String>();
rgbList.add("Red");
rgbList.add("Green");
rgbList.add("Blue");
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
for (String color : rgbList) {
rgbJoiner.add(color);
}
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}
@Test
public void whenMergeJoiners_thenReturnMerged() {
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
StringJoiner cmybJoiner = new StringJoiner(DELIMITER_HYPHEN, PREFIX, SUFFIX);
rgbJoiner.add("Red")
.add("Green")
.add("Blue");
cmybJoiner.add("Cyan")
.add("Magenta")
.add("Yellow")
.add("Black");
rgbJoiner.merge(cmybJoiner);
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
}
@Test
public void whenUsedWithinCollectors_thenJoin() {
List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
String commaSeparatedRGB = rgbList.stream()
.map(color -> color.toString())
.collect(Collectors.joining(","));
assertEquals(commaSeparatedRGB, "Red,Green,Blue");
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.stringpool;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class StringPoolUnitTest {
@Test
public void whenCreatingConstantStrings_thenTheirAddressesAreEqual() {
String constantString1 = "Baeldung";
String constantString2 = "Baeldung";
assertThat(constantString1).isSameAs(constantString2);
}
@Test
public void whenCreatingStringsWithTheNewOperator_thenTheirAddressesAreDifferent() {
String newString1 = new String("Baeldung");
String newString2 = new String("Baeldung");
assertThat(newString1).isNotSameAs(newString2);
}
@Test
public void whenComparingConstantAndNewStrings_thenTheirAddressesAreDifferent() {
String constantString = "Baeldung";
String newString = new String("Baeldung");
assertThat(constantString).isNotSameAs(newString);
}
@Test
public void whenInterningAStringWithIdenticalValueToAnother_thenTheirAddressesAreEqual() {
String constantString = "interned Baeldung";
String newString = new String("interned Baeldung");
assertThat(constantString).isNotSameAs(newString);
String internedString = newString.intern();
assertThat(constantString).isSameAs(internedString);
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.stringtokenizer;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class TokenizerUnitTest {
private final MyTokenizer myTokenizer = new MyTokenizer();
private final List<String> expectedTokensForString = Arrays.asList("Welcome", "to", "baeldung.com");
private final List<String> expectedTokensForFile = Arrays.asList("1", "IND", "India", "2", "MY", "Malaysia", "3", "AU", "Australia");
@Test
public void givenString_thenGetListOfString() {
String str = "Welcome,to,baeldung.com";
List<String> actualTokens = myTokenizer.getTokens(str);
assertEquals(expectedTokensForString, actualTokens);
}
@Test
public void givenFile_thenGetListOfString() {
List<String> actualTokens = myTokenizer.getTokensFromFile("data.csv", "|");
assertEquals(expectedTokensForFile, actualTokens);
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB