Move articles out of java-strings part3
This commit is contained in:
16
core-java-modules/core-java-string-algorithms/README.md
Normal file
16
core-java-modules/core-java-string-algorithms/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## Java String Algorithms
|
||||
|
||||
This module contains articles about string-related algorithms.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Check If a String Is a Palindrome](https://www.baeldung.com/java-palindrome)
|
||||
- [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars)
|
||||
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
|
||||
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
|
||||
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
|
||||
- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string)
|
||||
- [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)
|
||||
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
|
||||
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
|
||||
- More articles: [[next -->]](../core-java-string-algorithms-2)
|
||||
73
core-java-modules/core-java-string-algorithms/pom.xml
Normal file
73
core-java-modules/core-java-string-algorithms/pom.xml
Normal file
@@ -0,0 +1,73 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-string-algorithms</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-string-algorithms</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ahocorasick</groupId>
|
||||
<artifactId>ahocorasick</artifactId>
|
||||
<version>${ahocorasick.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.vdurmont</groupId>
|
||||
<artifactId>emoji-java</artifactId>
|
||||
<version>${emoji-java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-string-algorithms</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
<ahocorasick.version>0.4.0</ahocorasick.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<emoji-java.version>4.0.0</emoji-java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.matchwords;
|
||||
|
||||
import org.ahocorasick.trie.Emit;
|
||||
import org.ahocorasick.trie.Trie;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
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,66 @@
|
||||
package com.baeldung.palindrom;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.pangram;
|
||||
|
||||
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,102 @@
|
||||
package com.baeldung.removeduplicates;
|
||||
|
||||
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,29 @@
|
||||
package com.baeldung.repetition;
|
||||
|
||||
public class SubstringRepetition {
|
||||
|
||||
public static boolean containsOnlySubstrings(String string) {
|
||||
|
||||
if (string.length() < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
StringBuilder substr = new StringBuilder();
|
||||
for (int i = 0; i < string.length() / 2; i++) {
|
||||
substr.append(string.charAt(i));
|
||||
|
||||
String clearedFromSubstrings = string.replaceAll(substr.toString(), "");
|
||||
|
||||
if (clearedFromSubstrings.length() == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean containsOnlySubstringsEfficient(String string) {
|
||||
|
||||
return ((string + string).indexOf(string, 1) != string.length());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.reverse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class ReverseStringExamples {
|
||||
|
||||
public static String reverse(String input) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String output = "";
|
||||
|
||||
for (int i = input.length() - 1; i >= 0; i--) {
|
||||
output = output + input.charAt(i);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public static String reverseUsingStringBuilder(String input) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder output = new StringBuilder(input).reverse();
|
||||
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
public static String reverseUsingApacheCommons(String input) {
|
||||
return StringUtils.reverse(input);
|
||||
}
|
||||
|
||||
public static String reverseTheOrderOfWords(String sentence) {
|
||||
if (sentence == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
String[] words = sentence.split(" ");
|
||||
|
||||
for (int i = words.length - 1; i >= 0; i--) {
|
||||
output.append(words[i]);
|
||||
output.append(" ");
|
||||
}
|
||||
|
||||
return output.toString()
|
||||
.trim();
|
||||
}
|
||||
|
||||
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
|
||||
return StringUtils.reverseDelimited(sentence, ' ');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.searching;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class WordIndexer {
|
||||
|
||||
public List<Integer> findWord(String textString, String word) {
|
||||
int index = 0;
|
||||
List<Integer> indexes = new ArrayList<Integer>();
|
||||
String lowerCaseTextString = textString.toLowerCase();
|
||||
String lowerCaseWord = word.toLowerCase();
|
||||
|
||||
while(index != -1) {
|
||||
index = lowerCaseTextString.indexOf(lowerCaseWord, index);
|
||||
if (index == -1) {
|
||||
break;
|
||||
}
|
||||
|
||||
indexes.add(index);
|
||||
index++;
|
||||
}
|
||||
return indexes;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public List<Integer> findWordUpgrade(String textString, String word) {
|
||||
int index = 0;
|
||||
List<Integer> indexes = new ArrayList<Integer>();
|
||||
StringBuilder output = new StringBuilder();
|
||||
String lowerCaseTextString = textString.toLowerCase();
|
||||
String lowerCaseWord = word.toLowerCase();
|
||||
int wordLength = 0;
|
||||
|
||||
while(index != -1){
|
||||
index = lowerCaseTextString.indexOf(lowerCaseWord, index + wordLength); // Slight improvement
|
||||
if (index != -1) {
|
||||
indexes.add(index);
|
||||
}
|
||||
wordLength = word.length();
|
||||
}
|
||||
return indexes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.stopwords;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
|
||||
@Fork(value = 3, warmups = 1)
|
||||
@State(Scope.Benchmark)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
public class RemovingStopwordsPerformanceComparison {
|
||||
|
||||
private String data;
|
||||
|
||||
private List<String> stopwords;
|
||||
|
||||
private String stopwordsRegex;
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@Setup
|
||||
public void setup() throws IOException {
|
||||
data = new String(Files.readAllBytes(Paths.get("src/main/resources/shakespeare-hamlet.txt")));
|
||||
data = data.toLowerCase();
|
||||
stopwords = Files.readAllLines(Paths.get("src/main/resources/english_stopwords.txt"));
|
||||
stopwordsRegex = stopwords.stream().collect(Collectors.joining("|", "\\b(", ")\\b\\s?"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String removeManually() {
|
||||
String[] allWords = data.split(" ");
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for(String word:allWords) {
|
||||
if(! stopwords.contains(word)) {
|
||||
builder.append(word);
|
||||
builder.append(' ');
|
||||
}
|
||||
}
|
||||
return builder.toString().trim();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String removeAll() {
|
||||
ArrayList<String> allWords = Stream.of(data.split(" "))
|
||||
.collect(Collectors.toCollection(ArrayList<String>::new));
|
||||
allWords.removeAll(stopwords);
|
||||
return allWords.stream().collect(Collectors.joining(" "));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String replaceRegex() {
|
||||
return data.replaceAll(stopwordsRegex, "");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
i
|
||||
me
|
||||
my
|
||||
myself
|
||||
we
|
||||
our
|
||||
ours
|
||||
ourselves
|
||||
you
|
||||
your
|
||||
yours
|
||||
yourself
|
||||
yourselves
|
||||
he
|
||||
him
|
||||
his
|
||||
himself
|
||||
she
|
||||
her
|
||||
hers
|
||||
herself
|
||||
it
|
||||
its
|
||||
itself
|
||||
they
|
||||
them
|
||||
their
|
||||
theirs
|
||||
themselves
|
||||
what
|
||||
which
|
||||
who
|
||||
whom
|
||||
this
|
||||
that
|
||||
these
|
||||
those
|
||||
am
|
||||
is
|
||||
are
|
||||
was
|
||||
were
|
||||
be
|
||||
been
|
||||
being
|
||||
have
|
||||
has
|
||||
had
|
||||
having
|
||||
do
|
||||
does
|
||||
did
|
||||
doing
|
||||
a
|
||||
an
|
||||
the
|
||||
and
|
||||
but
|
||||
if
|
||||
or
|
||||
because
|
||||
as
|
||||
until
|
||||
while
|
||||
of
|
||||
at
|
||||
by
|
||||
for
|
||||
with
|
||||
about
|
||||
against
|
||||
between
|
||||
into
|
||||
through
|
||||
during
|
||||
before
|
||||
after
|
||||
above
|
||||
below
|
||||
to
|
||||
from
|
||||
up
|
||||
down
|
||||
in
|
||||
out
|
||||
on
|
||||
off
|
||||
over
|
||||
under
|
||||
again
|
||||
further
|
||||
then
|
||||
once
|
||||
here
|
||||
there
|
||||
when
|
||||
where
|
||||
why
|
||||
how
|
||||
all
|
||||
any
|
||||
both
|
||||
each
|
||||
few
|
||||
more
|
||||
most
|
||||
other
|
||||
some
|
||||
such
|
||||
no
|
||||
nor
|
||||
not
|
||||
only
|
||||
own
|
||||
same
|
||||
so
|
||||
than
|
||||
too
|
||||
very
|
||||
s
|
||||
t
|
||||
can
|
||||
will
|
||||
just
|
||||
don
|
||||
should
|
||||
now
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.matchwords;
|
||||
|
||||
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,98 @@
|
||||
package com.baeldung.palindrom;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.pangram;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
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,82 @@
|
||||
package com.baeldung.removeduplicates;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.removeemojis;
|
||||
|
||||
import com.vdurmont.emoji.EmojiParser;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
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,45 @@
|
||||
package com.baeldung.repetition;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.repetition.SubstringRepetition.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class SubstringRepetitionUnitTest {
|
||||
|
||||
private String validString = "aa";
|
||||
private String validStringTwo = "ababab";
|
||||
private String validStringThree = "baeldungbaeldung";
|
||||
|
||||
private String invalidString = "aca";
|
||||
private String invalidStringTwo = "ababa";
|
||||
private String invalidStringThree = "baeldungnonrepeatedbaeldung";
|
||||
|
||||
@Test
|
||||
public void givenValidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsTrue() {
|
||||
assertTrue(containsOnlySubstrings(validString));
|
||||
assertTrue(containsOnlySubstrings(validStringTwo));
|
||||
assertTrue(containsOnlySubstrings(validStringThree));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsFalse() {
|
||||
assertFalse(containsOnlySubstrings(invalidString));
|
||||
assertFalse(containsOnlySubstrings(invalidStringTwo));
|
||||
assertFalse(containsOnlySubstrings(invalidStringThree));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidStrings_whenCheckEfficientlyIfContainsOnlySubstrings_thenReturnsTrue() {
|
||||
assertTrue(containsOnlySubstringsEfficient(validString));
|
||||
assertTrue(containsOnlySubstringsEfficient(validStringTwo));
|
||||
assertTrue(containsOnlySubstringsEfficient(validStringThree));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidStrings_whenCheckEfficientlyIfContainsOnlySubstrings_thenReturnsFalse() {
|
||||
assertFalse(containsOnlySubstringsEfficient(invalidString));
|
||||
assertFalse(containsOnlySubstringsEfficient(invalidStringTwo));
|
||||
assertFalse(containsOnlySubstringsEfficient(invalidStringThree));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.reverse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ReverseStringExamplesUnitTest {
|
||||
|
||||
private static final String STRING_INPUT = "cat";
|
||||
private static final String STRING_INPUT_REVERSED = "tac";
|
||||
private static final String SENTENCE = "The quick brown fox jumps over the lazy dog";
|
||||
private static final String REVERSED_WORDS_SENTENCE = "dog lazy the over jumps fox brown quick The";
|
||||
|
||||
@Test
|
||||
public void whenReverseIsCalled_ThenCorrectStringIsReturned() {
|
||||
String reversed = ReverseStringExamples.reverse(STRING_INPUT);
|
||||
String reversedNull = ReverseStringExamples.reverse(null);
|
||||
String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY);
|
||||
|
||||
assertEquals(STRING_INPUT_REVERSED, reversed);
|
||||
assertEquals(null, reversedNull);
|
||||
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseUsingStringBuilderIsCalled_ThenCorrectStringIsReturned() throws Exception {
|
||||
String reversed = ReverseStringExamples.reverseUsingStringBuilder(STRING_INPUT);
|
||||
String reversedNull = ReverseStringExamples.reverseUsingStringBuilder(null);
|
||||
String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY);
|
||||
|
||||
assertEquals(STRING_INPUT_REVERSED, reversed);
|
||||
assertEquals(null, reversedNull);
|
||||
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() throws Exception {
|
||||
String reversed = ReverseStringExamples.reverseUsingApacheCommons(STRING_INPUT);
|
||||
String reversedNull = ReverseStringExamples.reverseUsingApacheCommons(null);
|
||||
String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY);
|
||||
|
||||
assertEquals(STRING_INPUT_REVERSED, reversed);
|
||||
assertEquals(null, reversedNull);
|
||||
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseTheOrderOfWordsIsCalled_ThenCorrectStringIsReturned() {
|
||||
String reversed = ReverseStringExamples.reverseTheOrderOfWords(SENTENCE);
|
||||
String reversedNull = ReverseStringExamples.reverseTheOrderOfWords(null);
|
||||
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY);
|
||||
|
||||
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
|
||||
assertEquals(null, reversedNull);
|
||||
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseTheOrderOfWordsUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() {
|
||||
String reversed = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(SENTENCE);
|
||||
String reversedNull = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(null);
|
||||
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY);
|
||||
|
||||
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
|
||||
assertEquals(null, reversedNull);
|
||||
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.searching;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
|
||||
public class WordIndexerUnitTest {
|
||||
|
||||
String theString;
|
||||
WordIndexer wordIndexer;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() throws Exception {
|
||||
wordIndexer = new WordIndexer();
|
||||
|
||||
theString = "To be, or not to be: that is the question: "
|
||||
+ "Whether 'tis nobler in the mind to suffer "
|
||||
+ "The slings and arrows of outrageous fortune, "
|
||||
+ "Or to take arms against a sea of troubles, "
|
||||
+ "And by opposing end them? To die: to sleep; "
|
||||
+ "No more; and by a sleep to say we end "
|
||||
+ "The heart-ache and the thousand natural shocks "
|
||||
+ "That flesh is heir to, 'tis a consummation "
|
||||
+ "Devoutly to be wish'd. To die, to sleep; "
|
||||
+ "To sleep: perchance to dream: ay, there's the rub: "
|
||||
+ "For in that sleep of death what dreams may come,";
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
public void givenWord_whenSearching_thenFindAllIndexedLocations() {
|
||||
List<Integer> expectedResult = Arrays.asList(7, 122, 130, 221, 438);
|
||||
|
||||
List<Integer> actualResult = wordIndexer.findWord(theString, "or");
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWordWithNoRepeatCharacters_whenImprovedSearching_thenFindAllIndexedLocations() {
|
||||
List<Integer> expectedResult = Arrays.asList(7, 122, 130, 221, 438);
|
||||
|
||||
List<Integer> actualResult = wordIndexer.findWordUpgrade(theString, "or");
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenWord_whenSearching_thenFindAtEndOfString() {
|
||||
List<Integer> expectedResult = Arrays.asList(480);
|
||||
|
||||
List<Integer> actualResult = wordIndexer.findWordUpgrade(theString, "come,");
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.stopwords;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class RemoveStopwordsUnitTest {
|
||||
final String original = "The quick brown fox jumps over the lazy dog";
|
||||
final String target = "quick brown fox jumps lazy dog";
|
||||
static List<String> stopwords;
|
||||
|
||||
@BeforeClass
|
||||
public static void loadStopwords() throws IOException {
|
||||
stopwords = Files.readAllLines(Paths.get("src/main/resources/english_stopwords.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveStopwordsManually_thenSuccess() {
|
||||
String[] allWords = original.toLowerCase()
|
||||
.split(" ");
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (String word : allWords) {
|
||||
if (!stopwords.contains(word)) {
|
||||
builder.append(word);
|
||||
builder.append(' ');
|
||||
}
|
||||
}
|
||||
|
||||
String result = builder.toString().trim();
|
||||
assertEquals(result, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveStopwordsUsingRemoveAll_thenSuccess() {
|
||||
ArrayList<String> allWords = Stream.of(original.toLowerCase()
|
||||
.split(" "))
|
||||
.collect(Collectors.toCollection(ArrayList<String>::new));
|
||||
allWords.removeAll(stopwords);
|
||||
String result = allWords.stream().collect(Collectors.joining(" "));
|
||||
assertEquals(result, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveStopwordsUsingRegex_thenSuccess() {
|
||||
String stopwordsRegex = stopwords.stream()
|
||||
.collect(Collectors.joining("|", "\\b(", ")\\b\\s?"));
|
||||
String result = original.toLowerCase().replaceAll(stopwordsRegex, "");
|
||||
assertEquals(result, target);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user