[BAEL-12899] - Splitted the java-strings module (#7410)
This commit is contained in:
committed by
Josh Cummings
parent
87ba90d455
commit
ec46f6de26
@@ -6,51 +6,18 @@
|
||||
- [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)
|
||||
- [Java String Conversions](https://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)
|
||||
- [Use char[] Array Over a String for Manipulating 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)
|
||||
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
|
||||
- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string)
|
||||
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
|
||||
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
|
||||
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
||||
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
|
||||
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
|
||||
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
|
||||
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
|
||||
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
|
||||
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
|
||||
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
|
||||
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
|
||||
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
|
||||
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
|
||||
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
|
||||
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
|
||||
- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
|
||||
- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list)
|
||||
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
|
||||
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
||||
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
|
||||
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
|
||||
- [Java toString() Method](https://www.baeldung.com/java-tostring)
|
||||
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
|
||||
- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
|
||||
- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
|
||||
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
|
||||
- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
|
||||
@@ -62,12 +62,6 @@
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.vdurmont</groupId>
|
||||
<artifactId>emoji-java</artifactId>
|
||||
<version>${emoji-java.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
@@ -83,24 +77,6 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Added for password generation -->
|
||||
<dependency>
|
||||
<groupId>org.passay</groupId>
|
||||
<artifactId>passay</artifactId>
|
||||
<version>${passay.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.ahocorasick</groupId>
|
||||
<artifactId>ahocorasick</artifactId>
|
||||
<version>${ahocorasick.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -134,11 +110,8 @@
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<icu4j.version>61.1</icu4j.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
<emoji-java.version>4.0.0</emoji-java.version>
|
||||
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
|
||||
<passay.version>1.3.1</passay.version>
|
||||
<commons-text.version>1.4</commons-text.version>
|
||||
<ahocorasick.version>0.4.0</ahocorasick.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class UseLocalDateTime {
|
||||
|
||||
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
|
||||
return LocalDateTime.parse(representation);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionX {
|
||||
|
||||
public String addCharUsingCharArray(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
int len = str.length();
|
||||
char[] updatedArr = new char[len + 1];
|
||||
str.getChars(0, position, updatedArr, 0);
|
||||
updatedArr[position] = ch;
|
||||
str.getChars(position, len, updatedArr, position + 1);
|
||||
return new String(updatedArr);
|
||||
}
|
||||
|
||||
public String addCharUsingSubstring(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
return str.substring(0, position) + ch + str.substring(position);
|
||||
}
|
||||
|
||||
public String addCharUsingStringBuilder(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
StringBuilder sb = new StringBuilder(str);
|
||||
sb.insert(position, ch);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void validate(String str, int position) {
|
||||
if (str == null) {
|
||||
throw new IllegalArgumentException("Str should not be null");
|
||||
}
|
||||
int len = str.length();
|
||||
if (position < 0 || position > len) {
|
||||
throw new IllegalArgumentException("position[" + position + "] should be "
|
||||
+ "in the range 0.." + len + " for string " + str);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.ahocorasick.trie.Emit;
|
||||
import org.ahocorasick.trie.Token;
|
||||
import org.ahocorasick.trie.Trie;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class MatchWords {
|
||||
|
||||
public static boolean containsWordsIndexOf(String inputString, String[] words) {
|
||||
boolean found = true;
|
||||
for (String word : words) {
|
||||
if (inputString.indexOf(word) == -1) {
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
public static boolean containsWords(String inputString, String[] items) {
|
||||
boolean found = true;
|
||||
for (String item : items) {
|
||||
if (!inputString.contains(item)) {
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
public static boolean containsWordsAhoCorasick(String inputString, String[] words) {
|
||||
Trie trie = Trie.builder()
|
||||
.onlyWholeWords()
|
||||
.addKeywords(words)
|
||||
.build();
|
||||
|
||||
Collection<Emit> emits = trie.parseText(inputString);
|
||||
emits.forEach(System.out::println);
|
||||
|
||||
boolean found = true;
|
||||
for(String word : words) {
|
||||
boolean contains = Arrays.toString(emits.toArray()).contains(word);
|
||||
if (!contains) {
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
public static boolean containsWordsPatternMatch(String inputString, String[] words) {
|
||||
|
||||
StringBuilder regexp = new StringBuilder();
|
||||
for (String word : words) {
|
||||
regexp.append("(?=.*").append(word).append(")");
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern.compile(regexp.toString());
|
||||
|
||||
return pattern.matcher(inputString).find();
|
||||
}
|
||||
|
||||
public static boolean containsWordsJava8(String inputString, String[] words) {
|
||||
List<String> inputStringList = Arrays.asList(inputString.split(" "));
|
||||
List<String> wordsList = Arrays.asList(words);
|
||||
|
||||
return wordsList.stream().allMatch(inputStringList::contains);
|
||||
}
|
||||
|
||||
public static boolean containsWordsArray(String inputString, String[] words) {
|
||||
List<String> inputStringList = Arrays.asList(inputString.split(" "));
|
||||
List<String> wordsList = Arrays.asList(words);
|
||||
|
||||
return inputStringList.containsAll(wordsList);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Pangram {
|
||||
private static final int ALPHABET_COUNT = 26;
|
||||
|
||||
public static boolean isPangram(String str) {
|
||||
if (str == null)
|
||||
return false;
|
||||
Boolean[] alphabetMarker = new Boolean[ALPHABET_COUNT];
|
||||
Arrays.fill(alphabetMarker, false);
|
||||
int alphabetIndex = 0;
|
||||
String strUpper = str.toUpperCase();
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
if ('A' <= strUpper.charAt(i) && strUpper.charAt(i) <= 'Z') {
|
||||
alphabetIndex = strUpper.charAt(i) - 'A';
|
||||
alphabetMarker[alphabetIndex] = true;
|
||||
}
|
||||
}
|
||||
for (boolean index : alphabetMarker) {
|
||||
if (!index)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isPangramWithStreams(String str) {
|
||||
if (str == null)
|
||||
return false;
|
||||
|
||||
// filtered character stream
|
||||
String strUpper = str.toUpperCase();
|
||||
Stream<Character> filteredCharStream = strUpper.chars()
|
||||
.filter(item -> ((item >= 'A' && item <= 'Z')))
|
||||
.mapToObj(c -> (char) c);
|
||||
Map<Character, Boolean> alphabetMap = filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1));
|
||||
|
||||
return (alphabetMap.size() == ALPHABET_COUNT);
|
||||
}
|
||||
|
||||
public static boolean isPerfectPangram(String str) {
|
||||
if (str == null)
|
||||
return false;
|
||||
|
||||
// filtered character stream
|
||||
String strUpper = str.toUpperCase();
|
||||
Stream<Character> filteredCharStream = strUpper.chars()
|
||||
.filter(item -> ((item >= 'A' && item <= 'Z')))
|
||||
.mapToObj(c -> (char) c);
|
||||
Map<Character, Long> alphabetFrequencyMap = filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
|
||||
|
||||
return (alphabetFrequencyMap.size() == ALPHABET_COUNT && alphabetFrequencyMap.values()
|
||||
.stream()
|
||||
.allMatch(item -> item == 1));
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.string.padding;
|
||||
|
||||
public class StringPaddingUtil {
|
||||
|
||||
public static String padLeftSpaces(String inputString, int length) {
|
||||
if (inputString.length() >= length) {
|
||||
return inputString;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (sb.length() < length - inputString.length()) {
|
||||
sb.append(' ');
|
||||
}
|
||||
sb.append(inputString);
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String padLeft(String inputString, int length) {
|
||||
if (inputString.length() >= length) {
|
||||
return inputString;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < length; i++) {
|
||||
sb.append(' ');
|
||||
}
|
||||
return sb.substring(inputString.length()) + inputString;
|
||||
}
|
||||
|
||||
public static String padLeftZeros(String inputString, int length) {
|
||||
return String
|
||||
.format("%1$" + length + "s", inputString)
|
||||
.replace(' ', '0');
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
package com.baeldung.string.password;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.text.RandomStringGenerator;
|
||||
import org.passay.CharacterData;
|
||||
import org.passay.CharacterRule;
|
||||
import org.passay.EnglishCharacterData;
|
||||
import org.passay.PasswordGenerator;
|
||||
|
||||
public class RandomPasswordGenerator {
|
||||
|
||||
/**
|
||||
* Special characters allowed in password.
|
||||
*/
|
||||
public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+";
|
||||
|
||||
public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS";
|
||||
|
||||
Random random = new SecureRandom();
|
||||
|
||||
public String generatePassayPassword() {
|
||||
PasswordGenerator gen = new PasswordGenerator();
|
||||
CharacterData lowerCaseChars = EnglishCharacterData.LowerCase;
|
||||
CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars);
|
||||
lowerCaseRule.setNumberOfCharacters(2);
|
||||
CharacterData upperCaseChars = EnglishCharacterData.UpperCase;
|
||||
CharacterRule upperCaseRule = new CharacterRule(upperCaseChars);
|
||||
upperCaseRule.setNumberOfCharacters(2);
|
||||
CharacterData digitChars = EnglishCharacterData.Digit;
|
||||
CharacterRule digitRule = new CharacterRule(digitChars);
|
||||
digitRule.setNumberOfCharacters(2);
|
||||
CharacterData specialChars = new CharacterData() {
|
||||
public String getErrorCode() {
|
||||
return ERROR_CODE;
|
||||
}
|
||||
|
||||
public String getCharacters() {
|
||||
return ALLOWED_SPL_CHARACTERS;
|
||||
}
|
||||
};
|
||||
CharacterRule splCharRule = new CharacterRule(specialChars);
|
||||
splCharRule.setNumberOfCharacters(2);
|
||||
String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule);
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateCommonTextPassword() {
|
||||
String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2))
|
||||
.concat(generateRandomAlphabet(2, true))
|
||||
.concat(generateRandomAlphabet(2, false))
|
||||
.concat(generateRandomCharacters(2));
|
||||
List<Character> pwChars = pwString.chars()
|
||||
.mapToObj(data -> (char) data)
|
||||
.collect(Collectors.toList());
|
||||
Collections.shuffle(pwChars);
|
||||
String password = pwChars.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateCommonsLang3Password() {
|
||||
String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true);
|
||||
String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true);
|
||||
String numbers = RandomStringUtils.randomNumeric(2);
|
||||
String specialChar = RandomStringUtils.random(2, 33, 47, false, false);
|
||||
String totalChars = RandomStringUtils.randomAlphanumeric(2);
|
||||
String combinedChars = upperCaseLetters.concat(lowerCaseLetters)
|
||||
.concat(numbers)
|
||||
.concat(specialChar)
|
||||
.concat(totalChars);
|
||||
List<Character> pwdChars = combinedChars.chars()
|
||||
.mapToObj(c -> (char) c)
|
||||
.collect(Collectors.toList());
|
||||
Collections.shuffle(pwdChars);
|
||||
String password = pwdChars.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateSecureRandomPassword() {
|
||||
Stream<Character> pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false))));
|
||||
List<Character> charList = pwdStream.collect(Collectors.toList());
|
||||
Collections.shuffle(charList);
|
||||
String password = charList.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateRandomSpecialCharacters(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomNumbers(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomCharacters(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomAlphabet(int length, boolean lowerCase) {
|
||||
int low;
|
||||
int hi;
|
||||
if (lowerCase) {
|
||||
low = 97;
|
||||
hi = 122;
|
||||
} else {
|
||||
low = 65;
|
||||
hi = 90;
|
||||
}
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomAlphabets(int count, boolean upperCase) {
|
||||
IntStream characters = null;
|
||||
if (upperCase) {
|
||||
characters = random.ints(count, 65, 90);
|
||||
} else {
|
||||
characters = random.ints(count, 97, 122);
|
||||
}
|
||||
return characters.mapToObj(data -> (char) data);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomNumbers(int count) {
|
||||
IntStream numbers = random.ints(count, 48, 57);
|
||||
return numbers.mapToObj(data -> (char) data);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomSpecialChars(int count) {
|
||||
IntStream specialChars = random.ints(count, 33, 45);
|
||||
return specialChars.mapToObj(data -> (char) data);
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package com.baeldung.string.removeleadingtrailingchar;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
|
||||
public class RemoveLeadingAndTrailingZeroes {
|
||||
|
||||
public static String removeLeadingZeroesWithStringBuilder(String s) {
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
|
||||
while (sb.length() > 1 && sb.charAt(0) == '0') {
|
||||
sb.deleteCharAt(0);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithStringBuilder(String s) {
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
|
||||
while (sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') {
|
||||
sb.setLength(sb.length() - 1);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithSubstring(String s) {
|
||||
int index = 0;
|
||||
|
||||
for (; index < s.length() - 1; index++) {
|
||||
if (s.charAt(index) != '0') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return s.substring(index);
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithSubstring(String s) {
|
||||
int index = s.length() - 1;
|
||||
|
||||
for (; index > 0; index--) {
|
||||
if (s.charAt(index) != '0') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return s.substring(0, index + 1);
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) {
|
||||
String stripped = StringUtils.stripStart(s, "0");
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) {
|
||||
String stripped = StringUtils.stripEnd(s, "0");
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) {
|
||||
String stripped = CharMatcher.is('0')
|
||||
.trimLeadingFrom(s);
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) {
|
||||
String stripped = CharMatcher.is('0')
|
||||
.trimTrailingFrom(s);
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithRegex(String s) {
|
||||
return s.replaceAll("^0+(?!$)", "");
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithRegex(String s) {
|
||||
return s.replaceAll("(?!^)0+$", "");
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class Customer {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CustomerArrayToString extends Customer {
|
||||
private Order[] orders;
|
||||
|
||||
public Order[] getOrders() {
|
||||
return orders;
|
||||
}
|
||||
public void setOrders(Order[] orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName()
|
||||
+ ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class CustomerComplexObjectToString extends Customer {
|
||||
private Order order;
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(Order order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [order=" + order + ", getFirstName()=" + getFirstName()
|
||||
+ ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class CustomerPrimitiveToString extends Customer {
|
||||
private long balance;
|
||||
|
||||
public long getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(long balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName()
|
||||
+ ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
public class CustomerReflectionToString extends Customer{
|
||||
|
||||
private Integer score;
|
||||
private List<String> orders;
|
||||
private StringBuffer fullname;
|
||||
|
||||
public Integer getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(Integer score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public List<String> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(List<String> orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
public StringBuffer getFullname() {
|
||||
return fullname;
|
||||
}
|
||||
|
||||
public void setFullname(StringBuffer fullname) {
|
||||
this.fullname = fullname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class CustomerWrapperCollectionToString extends Customer {
|
||||
private Integer score;
|
||||
private List<String> orders;
|
||||
private StringBuffer fullname;
|
||||
|
||||
public Integer getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(Integer score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public List<String> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(List<String> orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
public StringBuffer getFullname() {
|
||||
return fullname;
|
||||
}
|
||||
|
||||
public void setFullname(StringBuffer fullname) {
|
||||
this.fullname = fullname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname
|
||||
+ ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class Order {
|
||||
|
||||
private String orderId;
|
||||
private String desc;
|
||||
private long value;
|
||||
private String status;
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public long getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(long value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package com.baeldung.stringduplicates;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class RemoveDuplicateFromString {
|
||||
|
||||
|
||||
String removeDuplicatesUsingCharArray(String str) {
|
||||
|
||||
char[] chars = str.toCharArray();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int repeatedCtr;
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
repeatedCtr = 0;
|
||||
for (int j = i + 1; j < chars.length; j++) {
|
||||
if (chars[i] == chars[j]) {
|
||||
repeatedCtr++;
|
||||
}
|
||||
}
|
||||
if (repeatedCtr == 0) {
|
||||
sb.append(chars[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsinglinkedHashSet(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Set<Character> linkedHashSet = new LinkedHashSet<>();
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
linkedHashSet.add(str.charAt(i));
|
||||
}
|
||||
|
||||
for (Character c : linkedHashSet) {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingSorting(String str) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if(!str.isEmpty()) {
|
||||
char[] chars = str.toCharArray();
|
||||
Arrays.sort(chars);
|
||||
|
||||
sb.append(chars[0]);
|
||||
for (int i = 1; i < chars.length; i++) {
|
||||
if (chars[i] != chars[i - 1]) {
|
||||
sb.append(chars[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingHashSet(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Set<Character> hashSet = new HashSet<>();
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
hashSet.add(str.charAt(i));
|
||||
}
|
||||
|
||||
for (Character c : hashSet) {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingIndexOf(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int idx;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
idx = str.indexOf(c, i + 1);
|
||||
if (idx == -1) {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
String removeDuplicatesUsingDistinct(String str) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
str.chars().distinct().forEach(c -> sb.append((char) c));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ConvertStringToListUnitTest {
|
||||
|
||||
private final String countries = "Russia,Germany,England,France,Italy";
|
||||
private final String ranks = "1,2,3,4,5, 6,7";
|
||||
private final String emptyStrings = ",,,,,";
|
||||
private final List<String> expectedCountriesList = Arrays.asList("Russia", "Germany", "England", "France", "Italy");
|
||||
private final List<Integer> expectedRanksList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
private final List<String> expectedEmptyStringsList = Arrays.asList("", "", "", "", "", "");
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByJava() {
|
||||
List<String> convertedCountriesList = Arrays.asList(countries.split(",", -1));
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByApache() {
|
||||
List<String> convertedCountriesList = Arrays.asList(StringUtils.splitPreserveAllTokens(countries, ","));
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByGuava() {
|
||||
List<String> convertedCountriesList = Splitter.on(",")
|
||||
.trimResults()
|
||||
.splitToList(countries);
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByJava8() {
|
||||
List<String> convertedCountriesList = Stream.of(countries.split(",", -1))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByJava() {
|
||||
String[] convertedRankArray = ranks.split(",");
|
||||
List<Integer> convertedRankList = new ArrayList<Integer>();
|
||||
for (String number : convertedRankArray) {
|
||||
convertedRankList.add(Integer.parseInt(number.trim()));
|
||||
}
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByGuava() {
|
||||
List<Integer> convertedRankList = Lists.transform(Splitter.on(",")
|
||||
.trimResults()
|
||||
.splitToList(ranks), new Function<String, Integer>() {
|
||||
@Override
|
||||
public Integer apply(String input) {
|
||||
return Integer.parseInt(input.trim());
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByJava8() {
|
||||
List<Integer> convertedRankList = Stream.of(ranks.split(","))
|
||||
.map(String::trim)
|
||||
.map(Integer::parseInt)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByApache() {
|
||||
String[] convertedRankArray = StringUtils.split(ranks, ",");
|
||||
List<Integer> convertedRankList = new ArrayList<Integer>();
|
||||
for (String number : convertedRankArray) {
|
||||
convertedRankList.add(Integer.parseInt(number.trim()));
|
||||
}
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByJava() {
|
||||
List<String> convertedEmptyStringsList = Arrays.asList(emptyStrings.split(",", -1));
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByApache() {
|
||||
List<String> convertedEmptyStringsList = Arrays.asList(StringUtils.splitPreserveAllTokens(emptyStrings, ","));
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByGuava() {
|
||||
List<String> convertedEmptyStringsList = Splitter.on(",")
|
||||
.trimResults()
|
||||
.splitToList(emptyStrings);
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByJava8() {
|
||||
List<String> convertedEmptyStringsList = Stream.of(emptyStrings.split(",", -1))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringConcatenationUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenConcatUsingStringBuilder_checkStringCorrect() {
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder(100);
|
||||
stringBuilder.append("Baeldung");
|
||||
stringBuilder.append(" is");
|
||||
stringBuilder.append(" awesome");
|
||||
|
||||
assertEquals("Baeldung is awesome", stringBuilder.toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleString_whenConcatUsingAdditionOperator_checkStringCorrect() {
|
||||
|
||||
String myString = "The " + "quick " + "brown " + "fox...";
|
||||
|
||||
assertEquals("The quick brown fox...", myString);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenConcatUsingStringFormat_checkStringCorrect() {
|
||||
|
||||
String myString = String.format("%s %s %.2f %s %s, %s...", "I",
|
||||
"ate",
|
||||
2.5056302,
|
||||
"blueberry",
|
||||
"pies",
|
||||
"oops");
|
||||
|
||||
|
||||
assertEquals("I ate 2.51 blueberry pies, oops...", myString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenStringConcatUsed_checkStringCorrect() {
|
||||
|
||||
String myString = "Both".concat(" fickle")
|
||||
.concat(" dwarves")
|
||||
.concat(" jinx")
|
||||
.concat(" my")
|
||||
.concat(" pig")
|
||||
.concat(" quiz");
|
||||
|
||||
assertEquals("Both fickle dwarves jinx my pig quiz", myString);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenStringJoinUsed_checkStringCorrect() {
|
||||
|
||||
String[] strings = {"I'm", "running", "out", "of", "pangrams!"};
|
||||
|
||||
String myString = String.join(" ", strings);
|
||||
|
||||
assertEquals("I'm running out of pangrams!", myString);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenStringJoinerUsed_checkStringCorrect() {
|
||||
|
||||
StringJoiner fruitJoiner = new StringJoiner(", ");
|
||||
fruitJoiner.add("Apples");
|
||||
fruitJoiner.add("Oranges");
|
||||
fruitJoiner.add("Bananas");
|
||||
|
||||
assertEquals("Apples, Oranges, Bananas", fruitJoiner.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenArrayJoiner_checkStringCorrect() {
|
||||
|
||||
String[] myFavouriteLanguages = {"Java", "JavaScript", "Python"};
|
||||
|
||||
String toString = Arrays.toString(myFavouriteLanguages);
|
||||
|
||||
assertEquals("[Java, JavaScript, Python]", toString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayListOfStrings_whenCollectorsJoin_checkStringCorrect() {
|
||||
|
||||
List<String> awesomeAnimals = Arrays.asList("Shark", "Panda", "Armadillo");
|
||||
|
||||
String animalString = awesomeAnimals.stream().collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals("Shark, Panda, Armadillo", animalString);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
Relevant Articles:
|
||||
- [Java String Conversions](http://www.baeldung.com/java-string-conversions)
|
||||
@@ -1,128 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package com.baeldung.java.countingChars;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
|
||||
|
||||
/***
|
||||
* Example of counting chars in a String.
|
||||
*/
|
||||
public class CountCharsExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingLoop_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
char someChar = 'e';
|
||||
int count = 0;
|
||||
for (int i = 0; i < someString.length(); i++) {
|
||||
if (someString.charAt(i) == someChar) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingReplace_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
int count = someString.length() - someString.replace("e", "").length();
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingSplit_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
int count = someString.split("e", -1).length - 1;
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingReqExp_thenCountChars() {
|
||||
Pattern pattern = Pattern.compile("[^e]*e");
|
||||
Matcher matcher = pattern.matcher("elephant");
|
||||
int count = 0;
|
||||
while (matcher.find()) {
|
||||
count++;
|
||||
}
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingRecursion_thenCountChars() {
|
||||
int count = useRecursion("elephant", 'e', 0);
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
private int useRecursion(String someString, char searchedChar, int index) {
|
||||
if (index >= someString.length()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int count = someString.charAt(index) == searchedChar ? 1 : 0;
|
||||
return count + useRecursion(someString, searchedChar, index + 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingStringUtils_thenCountChars() throws InterruptedException {
|
||||
int count = StringUtils.countMatches("elephant", "e");
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingJava8Features_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
long count = someString.chars().filter(ch -> ch == 'e').count();
|
||||
assertEquals(2, count);
|
||||
|
||||
long count2 = someString.codePoints().filter(ch -> ch == 'e').count();
|
||||
assertEquals(2, count2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingGuavaCharMatcher_thenCountChars() {
|
||||
int count = CharMatcher.is('e').countIn("elephant");
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.baeldung.java8.base64;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringToByteArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArrayUsingStringClass_thenOk() {
|
||||
final String originalInput = "test input";
|
||||
byte[] result = originalInput.getBytes();
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
||||
assertEquals(originalInput.length(), result.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharset_whenConvertStringToByteArrayUsingStringClass_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
byte[] result = originalInput.getBytes(StandardCharsets.UTF_16);
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
||||
assertTrue(originalInput.length() < result.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArrayUsingBase64Decoder_thenOk() {
|
||||
final String originalInput = "dGVzdCBpbnB1dA==";
|
||||
byte[] result = Base64.getDecoder().decode(originalInput);
|
||||
|
||||
assertEquals("test input", new String(result));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArrayUsingDatatypeConverter_thenOk() {
|
||||
final String originalInput = "dGVzdCBpbnB1dA==";
|
||||
byte[] result = DatatypeConverter.parseBase64Binary(originalInput);
|
||||
|
||||
assertEquals("test input", new String(result));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArray_thenOk(){
|
||||
String originalInput = "7465737420696E707574";
|
||||
byte[] result = DatatypeConverter.parseHexBinary(originalInput);
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
||||
assertEquals("test input", new String(result));
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionXUnitTest {
|
||||
|
||||
private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
|
||||
private String word = "Titanc";
|
||||
private char letter = 'i';
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MatchWordsUnitTest {
|
||||
|
||||
private final String[] words = {"hello", "Baeldung"};
|
||||
private final String inputString = "hello there, Baeldung";
|
||||
private final String wholeInput = "helloBaeldung";
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingStringContains_shouldMatchWords() {
|
||||
final boolean result = MatchWords.containsWords(inputString, words);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingJava8_shouldMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsJava8(inputString, words);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingJava8_shouldNotMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsJava8(wholeInput, words);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingPattern_shouldMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsPatternMatch(inputString, words);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingAhoCorasick_shouldMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsAhoCorasick(inputString, words);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingAhoCorasick_shouldNotMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsAhoCorasick(wholeInput, words);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingIndexOf_shouldMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsIndexOf(inputString, words);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingArrayList_shouldMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsArray(inputString, words);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenCallingArrayList_shouldNotMatchWords() {
|
||||
final boolean result = MatchWords.containsWordsArray(wholeInput, words);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PangramUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenValidString_isPangram_shouldReturnSuccess() {
|
||||
String input = "Two driven jocks help fax my big quiz";
|
||||
assertTrue(Pangram.isPangram(input));
|
||||
assertTrue(Pangram.isPangramWithStreams(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullString_isPangram_shouldReturnFailure() {
|
||||
String input = null;
|
||||
assertFalse(Pangram.isPangram(input));
|
||||
assertFalse(Pangram.isPangramWithStreams(input));
|
||||
assertFalse(Pangram.isPerfectPangram(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPerfectPangramString_isPerfectPangram_shouldReturnSuccess() {
|
||||
String input = "abcdefghijklmNoPqrStuVwxyz";
|
||||
assertTrue(Pangram.isPerfectPangram(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonPangramString_isPangram_shouldReturnFailure() {
|
||||
String input = "invalid pangram";
|
||||
assertFalse(Pangram.isPangram(input));
|
||||
assertFalse(Pangram.isPangramWithStreams(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPangram_isPerfectPangram_shouldReturnFailure() {
|
||||
String input = "Two driven jocks help fax my big quiz";
|
||||
assertFalse(Pangram.isPerfectPangram(input));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.vdurmont.emoji.EmojiParser;
|
||||
|
||||
public class RemovingEmojiFromStringUnitTest {
|
||||
String text = "la conférence, commencera à 10 heures 😅";
|
||||
String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]";
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingLibrary_thenSuccess() {
|
||||
String result = EmojiParser.removeAllEmojis(text);
|
||||
System.out.println(result);
|
||||
assertEquals(result, "la conférence, commencera à 10 heures ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceEmojiUsingLibrary_thenSuccess() {
|
||||
String result = EmojiParser.parseToAliases(text);
|
||||
System.out.println(result);
|
||||
assertEquals(result, "la conférence, commencera à 10 heures :sweat_smile:");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingRegex_thenSuccess() {
|
||||
String result = text.replaceAll(regex, "");
|
||||
System.out.println(result);
|
||||
assertEquals(result, "la conférence, commencera à 10 heures ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingMatcher_thenSuccess() {
|
||||
Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
String result = matcher.replaceAll("");
|
||||
System.out.println(result);
|
||||
assertEquals(result, "la conférence, commencera à 10 heures ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingCodepoints_thenSuccess() {
|
||||
String result = text.replaceAll("[\\x{0001f300}-\\x{0001f64f}]|[\\x{0001f680}-\\x{0001f6ff}]", "");
|
||||
System.out.println(result);
|
||||
assertEquals(result, "la conférence, commencera à 10 heures ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingUnicode_thenSuccess() {
|
||||
String result = text.replaceAll("[\ud83c\udf00-\ud83d\ude4f]|[\ud83d\ude80-\ud83d\udeff]", "");
|
||||
System.out.println(result);
|
||||
assertEquals(result, "la conférence, commencera à 10 heures ");
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.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");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_Regex() {
|
||||
assertThat(" car , jeep, scooter ".trim()
|
||||
.split("\\s*,\\s*")).containsExactly("car", "jeep", "scooter");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_java_8() {
|
||||
assertThat(Arrays.stream(" car , jeep, scooter ".split(","))
|
||||
.map(String::trim)
|
||||
.toArray(String[]::new)).containsExactly("car", "jeep", "scooter");
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.primitives.Chars;
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.CharBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class StringFromPrimitiveArrayUnitTest {
|
||||
|
||||
private int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
|
||||
private char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
|
||||
|
||||
private char separatorChar = '-';
|
||||
|
||||
private String separator = String.valueOf(separatorChar);
|
||||
|
||||
private String expectedIntString = "1-2-3-4-5-6-7-8-9";
|
||||
|
||||
private String expectedCharString = "a-b-c-d-e-f";
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() {
|
||||
assertThat(Arrays.stream(intArray)
|
||||
.mapToObj(String::valueOf)
|
||||
.collect(Collectors.joining(separator)))
|
||||
.isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() {
|
||||
assertThat(CharBuffer.wrap(charArray).chars()
|
||||
.mapToObj(intChar -> String.valueOf((char) intChar))
|
||||
.collect(Collectors.joining(separator)))
|
||||
.isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void giveIntArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() {
|
||||
StringJoiner intStringJoiner = new StringJoiner(separator);
|
||||
|
||||
Arrays.stream(intArray)
|
||||
.mapToObj(String::valueOf)
|
||||
.forEach(intStringJoiner::add);
|
||||
|
||||
assertThat(intStringJoiner.toString()).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() {
|
||||
StringJoiner charStringJoiner = new StringJoiner(separator);
|
||||
|
||||
CharBuffer.wrap(charArray).chars()
|
||||
.mapToObj(intChar -> String.valueOf((char) intChar))
|
||||
.forEach(charStringJoiner::add);
|
||||
|
||||
assertThat(charStringJoiner.toString()).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() {
|
||||
assertThat(StringUtils.join(intArray, separatorChar)).isEqualTo(expectedIntString);
|
||||
assertThat(StringUtils.join(ArrayUtils.toObject(intArray), separator)).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() {
|
||||
assertThat(StringUtils.join(charArray, separatorChar)).isEqualTo(expectedCharString);
|
||||
assertThat(StringUtils.join(ArrayUtils.toObject(charArray), separator)).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() {
|
||||
assertThat(Joiner.on(separator).join(Ints.asList(intArray))).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() {
|
||||
assertThat(Joiner.on(separator).join(Chars.asList(charArray))).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() {
|
||||
assertThat(joinIntArrayWithStringBuilder(intArray, separator)).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() {
|
||||
assertThat(joinCharArrayWithStringBuilder(charArray, separator)).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
private String joinIntArrayWithStringBuilder(int[] array, String separator) {
|
||||
if (array.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
for (int i = 0; i < array.length - 1; i++) {
|
||||
stringBuilder.append(array[i]);
|
||||
stringBuilder.append(separator);
|
||||
}
|
||||
stringBuilder.append(array[array.length - 1]);
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
private String joinCharArrayWithStringBuilder(char[] array, String separator) {
|
||||
if (array.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
for (int i = 0; i < array.length - 1; i++) {
|
||||
stringBuilder.append(array[i]);
|
||||
stringBuilder.append(separator);
|
||||
}
|
||||
stringBuilder.append(array[array.length - 1]);
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SubstringUnitTest {
|
||||
|
||||
String text = "Julia Evans was born on 25-09-1984. She is currently living in the USA (United States of America).";
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedStringUtils_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("United States of America", StringUtils.substringBetween(text, "(", ")"));
|
||||
Assert.assertEquals("the USA (United States of America).", StringUtils.substringAfter(text, "living in "));
|
||||
Assert.assertEquals("Julia Evans", StringUtils.substringBefore(text, " was born"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedScanner_ShouldReturnProperSubstring() {
|
||||
try (Scanner scanner = new Scanner(text)) {
|
||||
scanner.useDelimiter("\\.");
|
||||
Assert.assertEquals("Julia Evans was born on 25-09-1984", scanner.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSplit_ShouldReturnProperSubstring() {
|
||||
String[] sentences = text.split("\\.");
|
||||
Assert.assertEquals("Julia Evans was born on 25-09-1984", sentences[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedRegex_ShouldReturnProperSubstring() {
|
||||
Pattern pattern = Pattern.compile("\\d{2}\\-\\d{2}-\\d{4}");
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
if (matcher.find()) {
|
||||
Assert.assertEquals("25-09-1984", matcher.group());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubSequence_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America)", text.subSequence(67, text.length() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstring_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America).", text.substring(67));
|
||||
Assert.assertEquals("USA (United States of America)", text.substring(67, text.length() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithIndexOf_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithLastIndexOf_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("1984", text.substring(text.lastIndexOf('-') + 1, text.indexOf('.')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithIndexOfAString_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America)", text.substring(text.indexOf("USA"), text.indexOf(')') + 1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
package com.baeldung.string.conversion;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ByteArrayToStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithDefaultCharset_thenOK() {
|
||||
final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114,
|
||||
108, 100, 33 };
|
||||
String string = new String(byteArrray);
|
||||
System.out.println(string);
|
||||
|
||||
assertNotNull(string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithNamedCharset_thenOK()
|
||||
throws UnsupportedEncodingException {
|
||||
final String charsetName = "IBM01140";
|
||||
final byte[] byteArrray = { -56, -123, -109, -109, -106, 64, -26, -106,
|
||||
-103, -109, -124, 90 };
|
||||
|
||||
String string = new String(byteArrray, charsetName);
|
||||
|
||||
assertEquals("Hello World!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithCharSet_thenOK() {
|
||||
final Charset charset = Charset.forName("UTF-8");
|
||||
final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114,
|
||||
108, 100, 33 };
|
||||
|
||||
String string = new String(byteArrray, charset);
|
||||
|
||||
assertEquals("Hello World!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithStandardCharSet_thenOK() {
|
||||
final Charset charset = StandardCharsets.UTF_16;
|
||||
|
||||
final byte[] byteArrray = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0,
|
||||
111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 };
|
||||
|
||||
String string = new String(byteArrray, charset);
|
||||
|
||||
assertEquals("Hello World!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDecodeWithCharset_thenOK() {
|
||||
byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33 };
|
||||
final Charset charset = StandardCharsets.US_ASCII;
|
||||
|
||||
String string = charset.decode(ByteBuffer.wrap(byteArrray)).toString();
|
||||
System.out.println(string);
|
||||
|
||||
assertEquals("Hello <20>orl<72>!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharsetDecoder_thenOK()
|
||||
throws CharacterCodingException {
|
||||
byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33};
|
||||
CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();
|
||||
|
||||
decoder.onMalformedInput(CodingErrorAction.REPLACE)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPLACE)
|
||||
.replaceWith("?");
|
||||
|
||||
String string = decoder.decode(ByteBuffer.wrap(byteArrray)).toString();
|
||||
|
||||
assertEquals("Hello ?orl?!", string);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package com.baeldung.string.conversion;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetEncoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringToByteArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithDefaultCharset_thenOK() {
|
||||
final String inputString = "Hello World!";
|
||||
final String defaultCharSet = Charset.defaultCharset()
|
||||
.displayName();
|
||||
|
||||
byte[] byteArrray = inputString.getBytes();
|
||||
|
||||
System.out.printf(
|
||||
"Using default charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
defaultCharSet, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertNotNull(byteArrray);
|
||||
assert (byteArrray.length >= inputString.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithNamedCharset_thenOK()
|
||||
throws UnsupportedEncodingException {
|
||||
final String inputString = "Hello World!";
|
||||
final String charsetName = "IBM01140";
|
||||
|
||||
byte[] byteArrray = inputString.getBytes("IBM01140");
|
||||
|
||||
System.out.printf(
|
||||
"Using named charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charsetName, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(new byte[] { -56, -123, -109, -109, -106, 64, -26,
|
||||
-106, -103, -109, -124, 90 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithCharset_thenOK() {
|
||||
final String inputString = "Hello ਸੰਸਾਰ!";
|
||||
final Charset charset = Charset.forName("ASCII");
|
||||
|
||||
byte[] byteArrray = inputString.getBytes(charset);
|
||||
|
||||
System.out.printf(
|
||||
"Using Charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charset, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(
|
||||
new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithStandardCharset_thenOK() {
|
||||
final String inputString = "Hello World!";
|
||||
final Charset charset = StandardCharsets.UTF_16;
|
||||
|
||||
byte[] byteArrray = inputString.getBytes(charset);
|
||||
|
||||
System.out.printf(
|
||||
"Using Standard Charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charset, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0,
|
||||
111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEncodeWithCharset_thenOK() {
|
||||
final String inputString = "Hello ਸੰਸਾਰ!";
|
||||
final Charset charset = StandardCharsets.US_ASCII;
|
||||
|
||||
byte[] byteArrray = charset.encode(inputString)
|
||||
.array();
|
||||
|
||||
System.out.printf(
|
||||
"Using encode with Charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charset, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(
|
||||
new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharsetEncoder_thenOK()
|
||||
throws CharacterCodingException {
|
||||
final String inputString = "Hello ਸੰਸਾਰ!";
|
||||
CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();
|
||||
encoder.onMalformedInput(CodingErrorAction.IGNORE)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPLACE)
|
||||
.replaceWith(new byte[] { 0 });
|
||||
|
||||
byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString))
|
||||
.array();
|
||||
|
||||
System.out.printf(
|
||||
"Using encode with CharsetEncoder:%s, Input String:%s, Output byte array:%s\n",
|
||||
encoder, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(
|
||||
new byte[] { 72, 101, 108, 108, 111, 32, 0, 0, 0, 0, 0, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.baeldung.string.formatter;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateToStringFormatterUnitTest {
|
||||
|
||||
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
|
||||
private static final String EXPECTED_STRING_DATE = "Aug 1, 2018 12:00 PM";
|
||||
private static Date date;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2018, Calendar.AUGUST, 1, 12, 0);
|
||||
date = calendar.getTime();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingSimpleDateFormatToString_thenCorrect() {
|
||||
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
|
||||
String formattedDate = formatter.format(date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingDateFormatToString_thenCorrect() {
|
||||
String formattedDate = DateFormat
|
||||
.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US)
|
||||
.format(date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingFormatterToString_thenCorrect() {
|
||||
String formattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingDateTimeApiToString_thenCorrect() {
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DATE_FORMAT);
|
||||
Instant instant = date.toInstant();
|
||||
LocalDateTime ldt = instant
|
||||
.atZone(ZoneId.of("CET"))
|
||||
.toLocalDateTime();
|
||||
String formattedDate = ldt.format(fmt);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Locale;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocaleUnitTest {
|
||||
@Test
|
||||
public void whenUsingLocal_thenCorrectResultsForDifferentLocale() {
|
||||
Locale usLocale = Locale.US;
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getCurrencyInstance(usLocale);
|
||||
assertEquals(usNumberFormat.format(number), "$102,300.46");
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringAnagramUnitTest {
|
||||
public boolean isAnagram(String s1, String s2) {
|
||||
if(s1.length() != s2.length())
|
||||
return false;
|
||||
|
||||
char[] arr1 = s1.toCharArray();
|
||||
char[] arr2 = s2.toCharArray();
|
||||
|
||||
Arrays.sort(arr1);
|
||||
Arrays.sort(arr2);
|
||||
|
||||
return Arrays.equals(arr1, arr2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestAnagrams_thenTestingCorrectly() {
|
||||
assertThat(isAnagram("car", "arc")).isTrue();
|
||||
assertThat(isAnagram("west", "stew")).isTrue();
|
||||
assertThat(isAnagram("west", "east")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringChangeCaseUnitTest {
|
||||
@Test
|
||||
public void givenString_whenChangingToUppercase_thenCaseChanged() {
|
||||
String s = "Welcome to Baeldung!";
|
||||
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenString_whenChangingToLowerrcase_thenCaseChanged() {
|
||||
String s = "Welcome to Baeldung!";
|
||||
assertEquals("welcome to baeldung!", s.toLowerCase());
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringCountOccurrencesUnitTest {
|
||||
public int countOccurrences(String s, char c) {
|
||||
int count = 0;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
if (s.charAt(i) == c) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCountingFrequencyOfChar_thenCountCorrect() {
|
||||
assertEquals(3, countOccurrences("united states", 't'));
|
||||
}
|
||||
|
||||
public void givenString_whenUsingJava8_thenCountingOfCharCorrect() {
|
||||
String str = "united states";
|
||||
long count = str.chars().filter(ch -> (char)ch == 't').count();
|
||||
assertEquals(3, count);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringFormatUnitTest {
|
||||
@Test
|
||||
public void givenString_whenUsingStringFormat_thenStringFormatted() {
|
||||
String title = "Baeldung";
|
||||
String formatted = String.format("Title is %s", title);
|
||||
assertEquals(formatted, "Title is Baeldung");
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringInternUnitTest {
|
||||
@Test
|
||||
public void whenCallingStringIntern_thenStringsInterned() {
|
||||
String s1 = "Baeldung";
|
||||
String s2 = new String("Baeldung");
|
||||
String s3 = new String("Baeldung").intern();
|
||||
|
||||
assertThat(s1 == s2).isFalse();
|
||||
assertThat(s1 == s3).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringJoinerUnitTest {
|
||||
@Test
|
||||
public void whenUsingStringJoiner_thenStringsJoined() {
|
||||
StringJoiner joiner = new StringJoiner(",", "[", "]");
|
||||
joiner.add("Red")
|
||||
.add("Green")
|
||||
.add("Blue");
|
||||
|
||||
assertEquals(joiner.toString(), "[Red,Green,Blue]");
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringPalindromeUnitTest {
|
||||
|
||||
public boolean isPalindrome(String text) {
|
||||
int forward = 0;
|
||||
int backward = text.length() - 1;
|
||||
while (backward > forward) {
|
||||
char forwardChar = text.charAt(forward++);
|
||||
char backwardChar = text.charAt(backward--);
|
||||
if (forwardChar != backwardChar)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIsPalindromeMethod_whenCheckingString_thenFindIfPalindrome() {
|
||||
assertThat(isPalindrome("madam")).isTrue();
|
||||
assertThat(isPalindrome("radar")).isTrue();
|
||||
assertThat(isPalindrome("level")).isTrue();
|
||||
|
||||
assertThat(isPalindrome("baeldung")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringReverseUnitTest {
|
||||
@Test
|
||||
public void whenUsingInbuildMethods_thenStringReversed() {
|
||||
String reversed = new StringBuilder("baeldung").reverse().toString();
|
||||
assertEquals("gnudleab", reversed);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class StringSplitUnitTest {
|
||||
@Test
|
||||
public void givenCoreJava_whenSplittingStrings_thenSplitted() {
|
||||
String expected[] = {
|
||||
"john",
|
||||
"peter",
|
||||
"mary"
|
||||
};
|
||||
|
||||
String[] splitted = "john,peter,mary".split(",");
|
||||
assertArrayEquals( expected, splitted );
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenApacheCommons_whenSplittingStrings_thenSplitted() {
|
||||
String expected[] = {
|
||||
"john",
|
||||
"peter",
|
||||
"mary"
|
||||
};
|
||||
String[] splitted = StringUtils.split("john peter mary");
|
||||
assertArrayEquals( expected, splitted );
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringToByteArrayUnitTest {
|
||||
@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);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringToCharArrayUnitTest {
|
||||
@Test
|
||||
public void whenConvertingStringToCharArray_thenConversionSuccessful() {
|
||||
String beforeConvStr = "hello";
|
||||
char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' };
|
||||
|
||||
assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.string.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringToIntegerUnitTest {
|
||||
@Test
|
||||
public void givenString_whenParsingInt_shouldConvertToInt() {
|
||||
String givenString = "42";
|
||||
|
||||
int result = Integer.parseInt(givenString);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.string.padding;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringPaddingUtilUnitTest {
|
||||
|
||||
String inputString = "123456";
|
||||
String expectedPaddedStringSpaces = " 123456";
|
||||
String expectedPaddedStringZeros = "0000123456";
|
||||
int minPaddedStringLength = 10;
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpaces_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, StringPaddingUtil.padLeftSpaces(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpacesUsingSubstring_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, StringPaddingUtil.padLeft(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithZeros_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringZeros, StringPaddingUtil.padLeftZeros(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpacesUsingStringUtils_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, StringUtils.leftPad(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithZerosUsingStringUtils_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringZeros, StringUtils.leftPad(inputString, minPaddedStringLength, "0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpacesUsingGuavaStrings_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, Strings.padStart(inputString, minPaddedStringLength, ' '));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithZerosUsingGuavaStrings_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringZeros, Strings.padStart(inputString, minPaddedStringLength, '0'));
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package com.baeldung.string.password;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Examples of passwords conforming to various specifications, using different libraries.
|
||||
*
|
||||
*/
|
||||
public class StringPasswordUnitTest {
|
||||
|
||||
RandomPasswordGenerator passGen = new RandomPasswordGenerator();
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingPassay_thenSuccessful() {
|
||||
String password = passGen.generatePassayPassword();
|
||||
int specialCharCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 33 || c <= 47) {
|
||||
specialCharCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in Passay", specialCharCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingCommonsText_thenSuccessful() {
|
||||
RandomPasswordGenerator passGen = new RandomPasswordGenerator();
|
||||
String password = passGen.generateCommonTextPassword();
|
||||
int lowerCaseCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 97 || c <= 122) {
|
||||
lowerCaseCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in commons-text ", lowerCaseCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingCommonsLang3_thenSuccessful() {
|
||||
String password = passGen.generateCommonsLang3Password();
|
||||
int numCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 48 || c <= 57) {
|
||||
numCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in commons-lang3", numCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingSecureRandom_thenSuccessful() {
|
||||
String password = passGen.generateSecureRandomPassword();
|
||||
int specialCharCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 33 || c <= 47) {
|
||||
specialCharCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in Secure Random", specialCharCount >= 2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package com.baeldung.string.removeleadingtrailingchar;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
public class RemoveLeadingAndTrailingZeroesUnitTest {
|
||||
|
||||
public static Stream<Arguments> leadingZeroTestProvider() {
|
||||
return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("0abc", "abc"), Arguments.of("0123", "123"), Arguments.of("0000123", "123"), Arguments.of("1230", "1230"), Arguments.of("01230", "1230"), Arguments.of("01", "1"),
|
||||
Arguments.of("0001", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "12034"), Arguments.of("1203400", "1203400"));
|
||||
}
|
||||
|
||||
public static Stream<Arguments> trailingZeroTestProvider() {
|
||||
return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("abc0", "abc"), Arguments.of("1230", "123"), Arguments.of("1230000", "123"), Arguments.of("0123", "0123"), Arguments.of("01230", "0123"), Arguments.of("10", "1"),
|
||||
Arguments.of("1000", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "0012034"), Arguments.of("1203400", "12034"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithStringBuilder_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithStringBuilder(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithStringBuilder_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithStringBuilder(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithSubstring_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithSubstring(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithSubstring_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithSubstring(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithApacheCommonsStripStart_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithApacheCommonsStripStart(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithApacheCommonsStripEnd_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithApacheCommonsStripEnd(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithGuavaTrimLeadingFrom_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithGuavaTrimLeadingFrom(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithGuavaTrimTrailingFrom_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithGuavaTrimTrailingFrom(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithRegex_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithRegex(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithRegex_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithRegex(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerArrayToStringUnitTest {
|
||||
private static final String CUSTOMER_ARRAY_TO_STRING
|
||||
= "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenArray_whenToString_thenCustomerDetails() {
|
||||
CustomerArrayToString customer = new CustomerArrayToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
Order[] orders = new Order[1];
|
||||
orders[0] = new Order();
|
||||
orders[0].setOrderId("A1111");
|
||||
orders[0].setDesc("Game");
|
||||
orders[0].setStatus("In-Shiping");
|
||||
customer.setOrders(orders);
|
||||
|
||||
assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerComplexObjectToStringUnitTest {
|
||||
private static final String CUSTOMER_COMPLEX_TO_STRING
|
||||
= "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenComplex_whenToString_thenCustomerDetails() {
|
||||
CustomerComplexObjectToString customer = new CustomerComplexObjectToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
Order order = new Order();
|
||||
order.setOrderId("A1111");
|
||||
order.setDesc("Game");
|
||||
order.setStatus("In-Shiping");
|
||||
customer.setOrder(order);
|
||||
|
||||
assertEquals(CUSTOMER_COMPLEX_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerPrimitiveToStringUnitTest {
|
||||
|
||||
private static final String CUSTOMER_PRIMITIVE_TO_STRING
|
||||
= "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenPrimitive_whenToString_thenCustomerDetails() {
|
||||
CustomerPrimitiveToString customer = new CustomerPrimitiveToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
customer.setBalance(110);
|
||||
|
||||
assertEquals(CUSTOMER_PRIMITIVE_TO_STRING, customer.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerWrapperCollectionToStringUnitTest {
|
||||
private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING
|
||||
= "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() {
|
||||
CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
customer.setScore(8);
|
||||
|
||||
List<String> orders = new ArrayList<String>();
|
||||
orders.add("Book");
|
||||
orders.add("Pen");
|
||||
customer.setOrders(orders);
|
||||
|
||||
StringBuffer fullname = new StringBuffer();
|
||||
fullname.append(customer.getLastName()+", "+ customer.getFirstName());
|
||||
customer.setFullname(fullname);
|
||||
|
||||
assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.baeldung.stringduplicates;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RemoveDuplicateFromStringUnitTest {
|
||||
|
||||
private final static String STR1 = "racecar";
|
||||
private final static String STR2 = "J2ee programming";
|
||||
private final static String STR_EMPTY = "";
|
||||
|
||||
private RemoveDuplicateFromString removeDuplicateFromString;
|
||||
|
||||
@Before
|
||||
public void executedBeforeEach() {
|
||||
removeDuplicateFromString = new RemoveDuplicateFromString();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenUsingCharArray_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("ecar", str1);
|
||||
Assert.assertEquals("J2e poraming", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingLinkedHashSet_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR2);
|
||||
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("race", str1);
|
||||
Assert.assertEquals("J2e progamin", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSorting_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR2);
|
||||
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingSorting(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("acer", str1);
|
||||
Assert.assertEquals(" 2Jaegimnopr", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHashSet_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("arce", str1);
|
||||
Assert.assertEquals(" pa2regiJmno", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingIndexOf_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("ecar", str1);
|
||||
Assert.assertEquals("J2e poraming", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJava8_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("race", str1);
|
||||
Assert.assertEquals("J2e progamin", str2);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.8 KiB |
Reference in New Issue
Block a user