Move articles out of java-strings part3
This commit is contained in:
16
core-java-modules/core-java-string-algorithms-2/README.md
Normal file
16
core-java-modules/core-java-string-algorithms-2/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## Java String Algorithms
|
||||
|
||||
This module contains articles about string-related algorithms.
|
||||
|
||||
### Relevant Articles:
|
||||
- [How to Remove the Last Character of a String?](https://www.baeldung.com/java-remove-last-character-of-string)
|
||||
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
||||
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
|
||||
- [Remove or Replace Part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
|
||||
- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
|
||||
- [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 Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
|
||||
- [Counting Words in a String](https://www.baeldung.com/java-word-counting)
|
||||
- [Finding the Difference Between Two Strings](https://www.baeldung.com/java-difference-between-two-strings)
|
||||
- More articles: [[<-- prev]](../core-java-string-algorithms)
|
||||
67
core-java-modules/core-java-string-algorithms-2/pom.xml
Normal file
67
core-java-modules/core-java-string-algorithms-2/pom.xml
Normal file
@@ -0,0 +1,67 @@
|
||||
<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-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-string-algorithms-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.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>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bitbucket.cowwoc</groupId>
|
||||
<artifactId>diff-match-patch</artifactId>
|
||||
<version>${diff-match-path.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-string-algorithms-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<diff-match-path.version>1.2</diff-match-path.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.addchar;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionX {
|
||||
|
||||
public String addCharUsingCharArray(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
int len = str.length();
|
||||
char[] updatedArr = new char[len + 1];
|
||||
str.getChars(0, position, updatedArr, 0);
|
||||
updatedArr[position] = ch;
|
||||
str.getChars(position, len, updatedArr, position + 1);
|
||||
return new String(updatedArr);
|
||||
}
|
||||
|
||||
public String addCharUsingSubstring(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
return str.substring(0, position) + ch + str.substring(position);
|
||||
}
|
||||
|
||||
public String addCharUsingStringBuilder(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
StringBuilder sb = new StringBuilder(str);
|
||||
sb.insert(position, ch);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void validate(String str, int position) {
|
||||
if (str == null) {
|
||||
throw new IllegalArgumentException("Str should not be null");
|
||||
}
|
||||
int len = str.length();
|
||||
if (position < 0 || position > len) {
|
||||
throw new IllegalArgumentException("position[" + position + "] should be " + "in the range 0.." + len + " for string " + str);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.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,26 @@
|
||||
package com.baeldung.removelastchar;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
class StringHelper {
|
||||
static String removeLastChar(String s) {
|
||||
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
|
||||
}
|
||||
|
||||
static String removeLastCharRegex(String s) {
|
||||
return (s == null) ? s : s.replaceAll(".$", "");
|
||||
}
|
||||
|
||||
static String removeLastCharOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.filter(str -> str.length() != 0)
|
||||
.map(str -> str.substring(0, str.length() - 1))
|
||||
.orElse(s);
|
||||
}
|
||||
|
||||
static String removeLastCharRegexOptional(String s) {
|
||||
return Optional.ofNullable(s)
|
||||
.map(str -> str.replaceAll(".$", ""))
|
||||
.orElse(s);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.baeldung.removeleadingtrailingchar;
|
||||
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
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,29 @@
|
||||
package com.baeldung.replacechar;
|
||||
|
||||
public class ReplaceCharacterInString {
|
||||
|
||||
public String replaceCharSubstring(String str, char ch, int index) {
|
||||
String myString = str.substring(0, index) + ch + str.substring(index + 1);
|
||||
return myString;
|
||||
}
|
||||
|
||||
public String replaceCharUsingCharArray(String str, char ch, int index) {
|
||||
char[] chars = str.toCharArray();
|
||||
chars[index] = ch;
|
||||
return String.valueOf(chars);
|
||||
}
|
||||
|
||||
|
||||
public String replaceCharStringBuilder(String str, char ch, int index) {
|
||||
StringBuilder myString = new StringBuilder(str);
|
||||
myString.setCharAt(index, ch);
|
||||
return myString.toString();
|
||||
}
|
||||
|
||||
public String replaceCharStringBuffer(String str, char ch, int index) {
|
||||
StringBuffer myString = new StringBuffer(str);
|
||||
myString.setCharAt(index, ch);
|
||||
return myString.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.wordcount;
|
||||
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
public class WordCounter {
|
||||
static final int WORD = 0;
|
||||
static final int SEPARATOR = 1;
|
||||
|
||||
public static int countWordsUsingRegex(String arg) {
|
||||
if (arg == null) {
|
||||
return 0;
|
||||
}
|
||||
final String[] words = arg.split("[\\pP\\s&&[^']]+");
|
||||
return words.length;
|
||||
}
|
||||
|
||||
public static int countWordsUsingTokenizer(String arg) {
|
||||
if (arg == null) {
|
||||
return 0;
|
||||
}
|
||||
final StringTokenizer stringTokenizer = new StringTokenizer(arg);
|
||||
return stringTokenizer.countTokens();
|
||||
}
|
||||
|
||||
public static int countWordsManually(String arg) {
|
||||
if (arg == null) {
|
||||
return 0;
|
||||
}
|
||||
int flag = SEPARATOR;
|
||||
int count = 0;
|
||||
int stringLength = arg.length();
|
||||
int characterCounter = 0;
|
||||
|
||||
while (characterCounter < stringLength) {
|
||||
if (isAllowedInWord(arg.charAt(characterCounter)) && flag == SEPARATOR) {
|
||||
flag = WORD;
|
||||
count++;
|
||||
} else if (!isAllowedInWord(arg.charAt(characterCounter))) {
|
||||
flag = SEPARATOR;
|
||||
}
|
||||
characterCounter++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static boolean isAllowedInWord(char charAt) {
|
||||
return charAt == '\'' || Character.isLetter(charAt);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.addchar;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionXUnitTest {
|
||||
|
||||
private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
|
||||
private String word = "Titanc";
|
||||
private char letter = 'i';
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.baeldung.containchar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static junit.framework.TestCase.assertFalse;
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
public class StringContainingCharactersUnitTest {
|
||||
|
||||
private static final Pattern[] inputRegexes = new Pattern[4];
|
||||
|
||||
private static final String regex = "^(?=.*?\\p{Lu})(?=.*?\\p{Ll})(?=.*?\\d)(?=.*?[`~!@#$%^&*()\\-_=+\\\\|\\[{\\]};:'\",<.>/?]).*$";
|
||||
|
||||
static {
|
||||
inputRegexes[0] = Pattern.compile(".*[A-Z].*");
|
||||
inputRegexes[1] = Pattern.compile(".*[a-z].*");
|
||||
inputRegexes[2] = Pattern.compile(".*\\d.*");
|
||||
inputRegexes[3] = Pattern.compile(".*[`~!@#$%^&*()\\-_=+\\\\|\\[{\\]};:'\",<.>/?].*");
|
||||
}
|
||||
|
||||
private static boolean isMatchingRegex(String input) {
|
||||
boolean inputMatches = true;
|
||||
for (Pattern inputRegex : inputRegexes) {
|
||||
if (!inputRegex
|
||||
.matcher(input)
|
||||
.matches()) {
|
||||
inputMatches = false;
|
||||
}
|
||||
}
|
||||
return inputMatches;
|
||||
}
|
||||
|
||||
private static boolean checkString(String input) {
|
||||
String specialChars = "~`!@#$%^&*()-_=+\\|[{]};:'\",<.>/?";
|
||||
char currentCharacter;
|
||||
boolean numberPresent = false;
|
||||
boolean upperCasePresent = false;
|
||||
boolean lowerCasePresent = false;
|
||||
boolean specialCharacterPresent = false;
|
||||
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
currentCharacter = input.charAt(i);
|
||||
if (Character.isDigit(currentCharacter)) {
|
||||
numberPresent = true;
|
||||
} else if (Character.isUpperCase(currentCharacter)) {
|
||||
upperCasePresent = true;
|
||||
} else if (Character.isLowerCase(currentCharacter)) {
|
||||
lowerCasePresent = true;
|
||||
} else if (specialChars.contains(String.valueOf(currentCharacter))) {
|
||||
specialCharacterPresent = true;
|
||||
}
|
||||
}
|
||||
|
||||
return numberPresent && upperCasePresent && lowerCasePresent && specialCharacterPresent;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexes_whenMatchingCorrectString_thenMatches() {
|
||||
String validInput = "Ab3;";
|
||||
assertTrue(isMatchingRegex(validInput));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexes_whenMatchingWrongStrings_thenNotMatching() {
|
||||
String invalidInput = "Ab3";
|
||||
assertFalse(isMatchingRegex(invalidInput));
|
||||
|
||||
invalidInput = "Ab;";
|
||||
assertFalse(isMatchingRegex(invalidInput));
|
||||
|
||||
invalidInput = "A3;";
|
||||
assertFalse(isMatchingRegex(invalidInput));
|
||||
|
||||
invalidInput = "b3;";
|
||||
assertFalse(isMatchingRegex(invalidInput));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidString_whenChecking_thenCorrect() {
|
||||
String validInput = "Ab3;";
|
||||
assertTrue(checkString(validInput));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidStrings_whenChecking_thenNotCorrect() {
|
||||
String invalidInput = "Ab3";
|
||||
assertFalse(checkString(invalidInput));
|
||||
|
||||
invalidInput = "Ab;";
|
||||
assertFalse(checkString(invalidInput));
|
||||
|
||||
invalidInput = "A3;";
|
||||
assertFalse(checkString(invalidInput));
|
||||
|
||||
invalidInput = "b3;";
|
||||
assertFalse(checkString(invalidInput));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleRegex_whenMatchingCorrectString_thenMatches() {
|
||||
String validInput = "Ab3;";
|
||||
assertTrue(Pattern
|
||||
.compile(regex)
|
||||
.matcher(validInput)
|
||||
.matches());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleRegex_whenMatchingWrongStrings_thenNotMatching() {
|
||||
String invalidInput = "Ab3";
|
||||
assertFalse(Pattern
|
||||
.compile(regex)
|
||||
.matcher(invalidInput)
|
||||
.matches());
|
||||
|
||||
invalidInput = "Ab;";
|
||||
assertFalse(Pattern
|
||||
.compile(regex)
|
||||
.matcher(invalidInput)
|
||||
.matches());
|
||||
|
||||
invalidInput = "A3;";
|
||||
assertFalse(Pattern
|
||||
.compile(regex)
|
||||
.matcher(invalidInput)
|
||||
.matches());
|
||||
|
||||
invalidInput = "b3;";
|
||||
assertFalse(Pattern
|
||||
.compile(regex)
|
||||
.matcher(invalidInput)
|
||||
.matches());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.baeldung.join;
|
||||
|
||||
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,50 @@
|
||||
package com.baeldung.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,93 @@
|
||||
package com.baeldung.removelastchar;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class RemoveLastCharUnitTest {
|
||||
|
||||
public static final String TEST_STRING = "abcdef";
|
||||
public static final String NULL_STRING = null;
|
||||
public static final String EMPTY_STRING = "";
|
||||
public static final String ONE_CHAR_STRING = "a";
|
||||
public static final String WHITE_SPACE_AT_THE_END_STRING = "abc ";
|
||||
public static final String NEW_LINE_AT_THE_END_STRING = "abc\n";
|
||||
public static final String MULTIPLE_LINES_STRING = "abc\ndef";
|
||||
|
||||
@Test
|
||||
public void givenTestString_whenSubstring_thenGetStingWithoutLastChar() {
|
||||
assertEquals("abcde", StringHelper.removeLastChar(TEST_STRING));
|
||||
assertEquals("abcde", StringUtils.substring(TEST_STRING, 0, TEST_STRING.length() - 1));
|
||||
assertEquals("abcde", StringUtils.chop(TEST_STRING));
|
||||
assertEquals("abcde", TEST_STRING.replaceAll(".$", ""));
|
||||
assertEquals("abcde", StringHelper.removeLastCharRegex(TEST_STRING));
|
||||
assertEquals("abcde", StringHelper.removeLastCharOptional(TEST_STRING));
|
||||
assertEquals("abcde", StringHelper.removeLastCharRegexOptional(TEST_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullString_whenSubstring_thenGetNullString() {
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastChar(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringUtils.chop(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastCharRegex(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastCharOptional(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastCharRegexOptional(NULL_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenSubstring_thenGetEmptyString() {
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastChar(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, StringUtils.substring(EMPTY_STRING, 0, EMPTY_STRING.length() - 1));
|
||||
assertEquals(EMPTY_STRING, StringUtils.chop(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, EMPTY_STRING.replaceAll(".$", ""));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegex(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharOptional(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegexOptional(EMPTY_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneCharString_whenSubstring_thenGetEmptyString() {
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastChar(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, StringUtils.substring(ONE_CHAR_STRING, 0, ONE_CHAR_STRING.length() - 1));
|
||||
assertEquals(EMPTY_STRING, StringUtils.chop(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, ONE_CHAR_STRING.replaceAll(".$", ""));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegex(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharOptional(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegexOptional(ONE_CHAR_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringWithWhiteSpaceAtTheEnd_whenSubstring_thenGetStringWithoutWhiteSpaceAtTheEnd() {
|
||||
assertEquals("abc", StringHelper.removeLastChar(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringUtils.substring(WHITE_SPACE_AT_THE_END_STRING, 0, WHITE_SPACE_AT_THE_END_STRING.length() - 1));
|
||||
assertEquals("abc", StringUtils.chop(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", WHITE_SPACE_AT_THE_END_STRING.replaceAll(".$", ""));
|
||||
assertEquals("abc", StringHelper.removeLastCharRegex(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringHelper.removeLastCharOptional(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringHelper.removeLastCharRegexOptional(WHITE_SPACE_AT_THE_END_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringWithNewLineAtTheEnd_whenSubstring_thenGetStringWithoutNewLine() {
|
||||
assertEquals("abc", StringHelper.removeLastChar(NEW_LINE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringUtils.substring(NEW_LINE_AT_THE_END_STRING, 0, NEW_LINE_AT_THE_END_STRING.length() - 1));
|
||||
assertEquals("abc", StringUtils.chop(NEW_LINE_AT_THE_END_STRING));
|
||||
assertNotEquals("abc", NEW_LINE_AT_THE_END_STRING.replaceAll(".$", ""));
|
||||
assertNotEquals("abc", StringHelper.removeLastCharRegex(NEW_LINE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringHelper.removeLastCharOptional(NEW_LINE_AT_THE_END_STRING));
|
||||
assertNotEquals("abc", StringHelper.removeLastCharRegexOptional(NEW_LINE_AT_THE_END_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiLineString_whenSubstring_thenGetStringWithoutNewLine() {
|
||||
assertEquals("abc\nde", StringHelper.removeLastChar(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", StringUtils.substring(MULTIPLE_LINES_STRING, 0, MULTIPLE_LINES_STRING.length() - 1));
|
||||
assertEquals("abc\nde", StringUtils.chop(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", MULTIPLE_LINES_STRING.replaceAll(".$", ""));
|
||||
assertEquals("abc\nde", StringHelper.removeLastCharRegex(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", StringHelper.removeLastCharOptional(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", StringHelper.removeLastCharRegexOptional(MULTIPLE_LINES_STRING));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.baeldung.removeleadingtrailingchar;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
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,30 @@
|
||||
package com.baeldung.replacechar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ReplaceCharInStringUnitTest {
|
||||
private ReplaceCharacterInString characterInString = new ReplaceCharacterInString();
|
||||
|
||||
@Test
|
||||
public void whenReplaceCharAtIndexUsingSubstring_thenSuccess() {
|
||||
assertEquals("abcme", characterInString.replaceCharSubstring("abcde", 'm', 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceCharAtIndexUsingCharArray_thenSuccess() {
|
||||
assertEquals("abcme", characterInString.replaceCharUsingCharArray("abcde", 'm', 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess() {
|
||||
assertEquals("abcme", characterInString.replaceCharStringBuilder("abcde", 'm', 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceCharAtIndexUsingStringBuffer_thenSuccess() {
|
||||
assertEquals("abcme", characterInString.replaceCharStringBuffer("abcde", 'm', 3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.replaceremove;
|
||||
|
||||
import org.apache.commons.lang3.RegExUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringReplaceAndRemoveUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplace_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
String processed = master.replace(target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
assertFalse(processed.contains(target));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
|
||||
|
||||
String master2 = "Welcome to Baeldung, Hello World Baeldung";
|
||||
String regexTarget = "(Baeldung)$";
|
||||
String replacement = "Java";
|
||||
String processed2 = master2.replaceAll(regexTarget, replacement);
|
||||
assertTrue(processed2.endsWith("Java"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
int startIndex = master.indexOf(target);
|
||||
int stopIndex = startIndex + target.length();
|
||||
|
||||
StringBuilder builder = new StringBuilder(master);
|
||||
|
||||
builder.delete(startIndex, stopIndex);
|
||||
assertFalse(builder.toString()
|
||||
.contains(target));
|
||||
|
||||
builder.replace(startIndex, stopIndex, replacement);
|
||||
assertTrue(builder.toString()
|
||||
.contains(replacement));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
String processed = StringUtils.replace(master, target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
|
||||
String master2 = "Hello World Baeldung!";
|
||||
String target2 = "baeldung";
|
||||
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
|
||||
assertFalse(processed2.contains(target));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplaceExactWord_thenProcessedString() {
|
||||
String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!";
|
||||
String regexTarget = "\\bcar\\b";
|
||||
String exactWordReplaced = sentence.replaceAll(regexTarget, "truck");
|
||||
assertTrue("A truck is not the same as a carriage, and some planes can carry cars inside them!".equals(exactWordReplaced));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplaceExactWordUsingRegExUtilsMethod_thenProcessedString() {
|
||||
String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!";
|
||||
String regexTarget = "\\bcar\\b";
|
||||
String exactWordReplaced = RegExUtils.replaceAll(sentence, regexTarget, "truck");
|
||||
assertTrue("A truck is not the same as a carriage, and some planes can carry cars inside them!".equals(exactWordReplaced));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.stringdiff;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
@State(Scope.Benchmark)
|
||||
public class StringDiffBenchmarkUnitTest {
|
||||
|
||||
private DiffMatchPatch diffMatchPatch = new DiffMatchPatch();
|
||||
|
||||
private List<String> inputs = randomizeInputs(10000);
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
Options opts = new OptionsBuilder().include(".*")
|
||||
.warmupIterations(1)
|
||||
.measurementIterations(50)
|
||||
.jvmArgs("-Xms2g", "-Xmx2g")
|
||||
.shouldDoGC(true)
|
||||
.forks(1)
|
||||
.build();
|
||||
|
||||
new Runner(opts).run();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int diffMatchPatch() {
|
||||
for (int i = 0; i < inputs.size() - 1; i++) {
|
||||
diffMatchPatch.diffMain(inputs.get(i), inputs.get(i + 1), false);
|
||||
}
|
||||
return inputs.size();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int stringUtils() {
|
||||
for (int i = 0; i < inputs.size() - 1; i++) {
|
||||
StringUtils.difference(inputs.get(i), inputs.get(i + 1));
|
||||
}
|
||||
return inputs.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a list of a given size, containing 30 character long strings,
|
||||
* each starting with a static prefix of 10 characters and followed by
|
||||
* a random 20 character suffix
|
||||
*
|
||||
* @return a {@link List} of randomised strings
|
||||
*/
|
||||
private List<String> randomizeInputs(int size) {
|
||||
String staticPart = "ABCDEF1234";
|
||||
List<String> inputs = new ArrayList<>();
|
||||
for (int i = 0; i < size; i++) {
|
||||
inputs.add(staticPart + RandomStringUtils.randomAlphabetic(20));
|
||||
}
|
||||
return inputs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.stringdiff;
|
||||
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch;
|
||||
import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch.Operation;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringDiffUnitTest {
|
||||
|
||||
private DiffMatchPatch diffMatchPatch = new DiffMatchPatch();
|
||||
|
||||
// Test samples
|
||||
private final String text1 = "ABCDELMN";
|
||||
private final String text2 = "ABCFGLMN";
|
||||
|
||||
@Test
|
||||
public void givenTwoStrings_whenDiffMatchPatch_thenReturnCorrectDiff() {
|
||||
assertThat(diffMatchPatch.diffMain(text1, text2, false), containsInAnyOrder(
|
||||
new DiffMatchPatch.Diff(Operation.EQUAL, "ABC"),
|
||||
new DiffMatchPatch.Diff(Operation.DELETE, "DE"),
|
||||
new DiffMatchPatch.Diff(Operation.INSERT, "FG"),
|
||||
new DiffMatchPatch.Diff(Operation.EQUAL, "LMN")));
|
||||
assertThat(diffMatchPatch.diffMain(text2, text1, false), containsInAnyOrder(
|
||||
new DiffMatchPatch.Diff(Operation.EQUAL, "ABC"),
|
||||
new DiffMatchPatch.Diff(Operation.INSERT, "DE"),
|
||||
new DiffMatchPatch.Diff(Operation.DELETE, "FG"),
|
||||
new DiffMatchPatch.Diff(Operation.EQUAL, "LMN")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStrings_whenStringUtilsDifference_thenReturnCorrectDiff() {
|
||||
assertThat(StringUtils.difference(text1, text2), is("FGLMN"));
|
||||
assertThat(StringUtils.difference(text2, text1), is("DELMN"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.wordcount;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
public class WordCountUnitTest {
|
||||
private String string1 = "This is a test sentence with eight words";
|
||||
private String string2 = "This#is%a test sentence with eight words";
|
||||
|
||||
@Test
|
||||
public void givenStringWith8Words_whenUsingRegexCount_ThenResultEqual8() {
|
||||
assertEquals(8, WordCounter.countWordsUsingRegex(string2));
|
||||
assertEquals(9, WordCounter.countWordsUsingRegex("no&one#should%ever-write-like,this;but:well"));
|
||||
assertEquals(7, WordCounter.countWordsUsingRegex("the farmer's wife--she was from Albuquerque"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringWith8Words_whenUsingManualMethod_ThenWordCountEqual8() {
|
||||
assertEquals(8, WordCounter.countWordsManually(string1));
|
||||
assertEquals(9, WordCounter.countWordsManually("no&one#should%ever-write-like,this but well"));
|
||||
assertEquals(7, WordCounter.countWordsManually("the farmer's wife--she was from Albuquerque"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStringWith8Words_whenUsingTokenizer_ThenWordCountEqual8() {
|
||||
assertEquals(8, WordCounter.countWordsUsingTokenizer(string1));
|
||||
assertEquals(3, new StringTokenizer("three blind mice").countTokens());
|
||||
assertEquals(4, new StringTokenizer("see\thow\tthey\trun").countTokens());
|
||||
assertEquals(7, new StringTokenizer("the farmer's wife--she was from Albuquerque", " -").countTokens());
|
||||
assertEquals(10, new StringTokenizer("did,you,ever,see,such,a,sight,in,your,life", ",").countTokens());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user