[BAEL-12899] - Splitted the java-strings module (#7410)
This commit is contained in:
committed by
Josh Cummings
parent
87ba90d455
commit
ec46f6de26
@@ -3,5 +3,20 @@
|
||||
- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
|
||||
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
|
||||
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
|
||||
- [Java – Generate Random String](http://www.baeldung.com/java-random-string)
|
||||
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
|
||||
- [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)
|
||||
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
|
||||
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
|
||||
- [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)
|
||||
- [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 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)
|
||||
- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
|
||||
- [String Initialization in Java](https://www.baeldung.com/java-string-initialization)
|
||||
|
||||
@@ -40,6 +40,16 @@
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
@@ -52,32 +62,54 @@
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<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>com.vdurmont</groupId>
|
||||
<artifactId>emoji-java</artifactId>
|
||||
<version>${emoji-java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ahocorasick</groupId>
|
||||
<artifactId>ahocorasick</artifactId>
|
||||
<version>${ahocorasick.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>2.0.0.Final</version>
|
||||
<version>${validation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.validator</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>6.0.2.Final</version>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<version>${javax.el-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.web</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>2.2.6</version>
|
||||
<version>${javax.el.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -105,9 +137,19 @@
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<passay.version>1.3.1</passay.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<emoji-java.version>4.0.0</emoji-java.version>
|
||||
<ahocorasick.version>0.4.0</ahocorasick.version>
|
||||
<icu4j.version>61.1</icu4j.version>
|
||||
<guava.version>28.0-jre</guava.version>
|
||||
<commons-text.version>1.4</commons-text.version>
|
||||
<validation-api.version>2.0.0.Final</validation-api.version>
|
||||
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<javax.el.version>2.2.6</javax.el.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,83 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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+$", "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.fileToBase64StringConversion;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileToBase64StringConversionUnitTest {
|
||||
|
||||
private String inputFilePath = "test_image.jpg";
|
||||
private String outputFilePath = "test_image_copy.jpg";
|
||||
|
||||
@Test
|
||||
public void fileToBase64StringConversion() throws IOException {
|
||||
//load file from /src/test/resources
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File inputFile = new File(classLoader
|
||||
.getResource(inputFilePath)
|
||||
.getFile());
|
||||
|
||||
byte[] fileContent = FileUtils.readFileToByteArray(inputFile);
|
||||
String encodedString = Base64
|
||||
.getEncoder()
|
||||
.encodeToString(fileContent);
|
||||
|
||||
//create output file
|
||||
File outputFile = new File(inputFile
|
||||
.getParentFile()
|
||||
.getAbsolutePath() + File.pathSeparator + outputFilePath);
|
||||
|
||||
// decode the string and write to file
|
||||
byte[] decodedBytes = Base64
|
||||
.getDecoder()
|
||||
.decode(encodedString);
|
||||
FileUtils.writeByteArrayToFile(outputFile, decodedBytes);
|
||||
|
||||
assertTrue(FileUtils.contentEquals(inputFile, outputFile));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.java8.base64;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ApacheCommonsEncodeDecodeUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final Base64 base64 = new Base64();
|
||||
final String encodedString = new String(base64.encode(originalInput.getBytes()));
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final Base64 base64 = new Base64();
|
||||
final String encodedString = new String(base64.encode(originalInput.getBytes()));
|
||||
|
||||
final String decodedString = new String(base64.decode(encodedString.getBytes()));
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedUsingStaticMethod() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedUsingStaticMethod_thenStringCanBeDecodedUsingStaticMethod() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
|
||||
|
||||
final String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.java8.base64;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8EncodeDecodeUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
|
||||
final String decodedString = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedWithoutPadding_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedWithoutPadding_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
|
||||
final String decodedString = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUrlIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
|
||||
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
|
||||
assertNotNull(encodedUrl);
|
||||
assertNotEquals(originalUrl, encodedUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUrlIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
|
||||
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl.getBytes());
|
||||
final String decodedUrl = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedUrl);
|
||||
assertEquals(originalUrl, decodedUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMimeIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final StringBuilder buffer = getMimeBuffer();
|
||||
|
||||
final byte[] forEncode = buffer.toString().getBytes();
|
||||
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
|
||||
|
||||
assertNotNull(encodedMime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMimeIsEncoded_thenItCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final StringBuilder buffer = getMimeBuffer();
|
||||
|
||||
final byte[] forEncode = buffer.toString().getBytes();
|
||||
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
|
||||
|
||||
final byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime);
|
||||
final String decodedMime = new String(decodedBytes);
|
||||
assertNotNull(decodedMime);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static StringBuilder getMimeBuffer() {
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
for (int count = 0; count < 10; ++count) {
|
||||
buffer.append(UUID.randomUUID().toString());
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
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 ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.baeldung.string.formatter;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Formatter;
|
||||
import java.util.GregorianCalendar;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringFormatterExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() {
|
||||
//Syntax of Format Specifiers for Date/Time Representation
|
||||
Calendar c = new GregorianCalendar(2017, 11, 10);
|
||||
String s = String.format("The date is: %tm %1$te,%1$tY", c);
|
||||
|
||||
|
||||
assertEquals("The date is: 12 10,2017", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenGeneralConversion_thenConvertedString() {
|
||||
//General Conversions
|
||||
String s = String.format("The correct answer is %s", false);
|
||||
assertEquals("The correct answer is false", s);
|
||||
|
||||
s = String.format("The correct answer is %b", null);
|
||||
assertEquals("The correct answer is false", s);
|
||||
|
||||
s = String.format("The correct answer is %B", true);
|
||||
assertEquals("The correct answer is TRUE", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCharConversion_thenConvertedString() {
|
||||
//Character Conversions
|
||||
String s = String.format("The correct answer is %c", 'a');
|
||||
assertEquals("The correct answer is a", s);
|
||||
|
||||
s = String.format("The correct answer is %c", null);
|
||||
assertEquals("The correct answer is null", s);
|
||||
|
||||
s = String.format("The correct answer is %C", 'b');
|
||||
assertEquals("The correct answer is B", s);
|
||||
|
||||
s = String.format("The valid unicode character: %c", 0x0400);
|
||||
assertTrue(Character.isValidCodePoint(0x0400));
|
||||
assertEquals("The valid unicode character: Ѐ", s);
|
||||
}
|
||||
|
||||
@Test(expected = java.util.IllegalFormatCodePointException.class)
|
||||
public void givenString_whenIllegalCodePointForConversion_thenError() {
|
||||
String s = String.format("The valid unicode character: %c", 0x11FFFF);
|
||||
assertFalse(Character.isValidCodePoint(0x11FFFF));
|
||||
assertEquals("The valid unicode character: Ā", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenNumericIntegralConversion_thenConvertedString() {
|
||||
//Numeric Integral Conversions
|
||||
String s = String.format("The number 25 in decimal = %d", 25);
|
||||
assertEquals("The number 25 in decimal = 25", s);
|
||||
|
||||
s = String.format("The number 25 in octal = %o", 25);
|
||||
assertEquals("The number 25 in octal = 31", s);
|
||||
|
||||
s = String.format("The number 25 in hexadecimal = %x", 25);
|
||||
assertEquals("The number 25 in hexadecimal = 19", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenNumericFloatingConversion_thenConvertedString() {
|
||||
//Numeric Floating-point Conversions
|
||||
String s = String.format("The computerized scientific format of 10000.00 "
|
||||
+ "= %e", 10000.00);
|
||||
assertEquals("The computerized scientific format of 10000.00 = 1.000000e+04", s);
|
||||
|
||||
s = String.format("The decimal format of 10.019 = %f", 10.019);
|
||||
assertEquals("The decimal format of 10.019 = 10.019000", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenLineSeparatorConversion_thenConvertedString() {
|
||||
//Line Separator Conversion
|
||||
String s = String.format("First Line %nSecond Line");
|
||||
assertEquals("First Line " + System.getProperty("line.separator")
|
||||
+ "Second Line", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSpecifyFlag_thenGotFormattedString() {
|
||||
//Without left-justified flag
|
||||
String s = String.format("Without left justified flag: %5d", 25);
|
||||
assertEquals("Without left justified flag: 25", s);
|
||||
|
||||
//Using left-justified flag
|
||||
s = String.format("With left justified flag: %-5d", 25);
|
||||
assertEquals("With left justified flag: 25 ", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSpecifyPrecision_thenGotExpected() {
|
||||
|
||||
//Precision
|
||||
String s = String.format("Output of 25.09878 with Precision 2: %.2f", 25.09878);
|
||||
assertEquals("Output of 25.09878 with Precision 2: 25.10", s);
|
||||
|
||||
s = String.format("Output of general conversion type with Precision 2: %.2b", true);
|
||||
assertEquals("Output of general conversion type with Precision 2: tr", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSpecifyArgumentIndex_thenGotExpected() {
|
||||
Calendar c = new GregorianCalendar(2017, 11, 10);
|
||||
//Argument_Index
|
||||
String s = String.format("The date is: %tm %1$te,%1$tY", c);
|
||||
assertEquals("The date is: 12 10,2017", s);
|
||||
|
||||
s = String.format("The date is: %tm %<te,%<tY", c);
|
||||
assertEquals("The date is: 12 10,2017", s);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAppendable_whenCreateFormatter_thenFormatterWorksOnAppendable() {
|
||||
//Using String Formatter with Appendable
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Formatter formatter = new Formatter(sb);
|
||||
formatter.format("I am writting to a %s Instance.", sb.getClass());
|
||||
assertEquals("I am writting to a class java.lang.StringBuilder Instance.", sb.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenNoArguments_thenExpected() {
|
||||
//Using String Formatter without arguments
|
||||
String s = String.format("John scored 90%% in Fall semester");
|
||||
assertEquals("John scored 90% in Fall semester", s);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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]");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
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 );
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
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'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
BIN
java-strings-2/src/test/resources/test_image.jpg
Normal file
BIN
java-strings-2/src/test/resources/test_image.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
Reference in New Issue
Block a user