Merge branch 'master' into BAEL-2313-String-to-byte-array
This commit is contained in:
@@ -36,3 +36,11 @@
|
||||
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
|
||||
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
|
||||
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
|
||||
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
|
||||
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
|
||||
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
|
||||
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
|
||||
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
|
||||
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
|
||||
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
|
||||
@@ -122,13 +122,13 @@
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<icu4j.version>61.1</icu4j.version>
|
||||
<guava.version>26.0-jre</guava.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
public class AddingNewLineToString {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String line1 = "Humpty Dumpty sat on a wall.";
|
||||
String line2 = "Humpty Dumpty had a great fall.";
|
||||
String rhyme = "";
|
||||
|
||||
System.out.println("***New Line in a String in Java***");
|
||||
//1. Using "\n"
|
||||
System.out.println("1. Using \\n");
|
||||
rhyme = line1 + "\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//2. Using "\r\n"
|
||||
System.out.println("2. Using \\r\\n");
|
||||
rhyme = line1 + "\r\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//3. Using "\r"
|
||||
System.out.println("3. Using \\r");
|
||||
rhyme = line1 + "\r" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//4. Using "\n\r" Note that this is not same as "\r\n"
|
||||
// Using "\n\r" is equivalent to adding two lines
|
||||
System.out.println("4. Using \\n\\r");
|
||||
rhyme = line1 + "\n\r" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//5. Using System.lineSeparator()
|
||||
System.out.println("5. Using System.lineSeparator()");
|
||||
rhyme = line1 + System.lineSeparator() + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//6. Using System.getProperty("line.separator")
|
||||
System.out.println("6. Using System.getProperty(\"line.separator\")");
|
||||
rhyme = line1 + System.getProperty("line.separator") + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
System.out.println("***HTML to rendered in a browser***");
|
||||
//1. Line break for HTML using <br>
|
||||
System.out.println("1. Line break for HTML using <br>");
|
||||
rhyme = line1 + "<br>" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//2. Line break for HTML using “ ”
|
||||
System.out.println("2. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//3. Line break for HTML using “ ”
|
||||
System.out.println("3. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//4. Line break for HTML using “
 ;”
|
||||
System.out.println("4. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//5. Line break for HTML using \n”
|
||||
System.out.println("5. Line break for HTML using \\n");
|
||||
rhyme = line1 + "\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.string.checkinputs;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class CheckIntegerInput {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
System.out.println("Enter an integer : ");
|
||||
|
||||
if (scanner.hasNextInt()) {
|
||||
System.out.println("You entered : " + scanner.nextInt());
|
||||
} else {
|
||||
System.out.println("The input is not an integer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.string.padding;
|
||||
|
||||
public class StringPaddingUtil {
|
||||
|
||||
public static String padLeftSpaces(String inputString, int length) {
|
||||
if (inputString.length() >= length) {
|
||||
return inputString;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (sb.length() < length - inputString.length()) {
|
||||
sb.append(' ');
|
||||
}
|
||||
sb.append(inputString);
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String padLeft(String inputString, int length) {
|
||||
if (inputString.length() >= length) {
|
||||
return inputString;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < length; i++) {
|
||||
sb.append(' ');
|
||||
}
|
||||
return sb.substring(inputString.length()) + inputString;
|
||||
}
|
||||
|
||||
public static String padLeftZeros(String inputString, int length) {
|
||||
return String
|
||||
.format("%1$" + length + "s", inputString)
|
||||
.replace(' ', '0');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.baeldung.string.removeleadingtrailingchar;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
|
||||
public class RemoveLeadingAndTrailingZeroes {
|
||||
|
||||
public static String removeLeadingZeroesWithStringBuilder(String s) {
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
|
||||
while (sb.length() > 1 && sb.charAt(0) == '0') {
|
||||
sb.deleteCharAt(0);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithStringBuilder(String s) {
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
|
||||
while (sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') {
|
||||
sb.setLength(sb.length() - 1);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithSubstring(String s) {
|
||||
int index = 0;
|
||||
|
||||
for (; index < s.length() - 1; index++) {
|
||||
if (s.charAt(index) != '0') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return s.substring(index);
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithSubstring(String s) {
|
||||
int index = s.length() - 1;
|
||||
|
||||
for (; index > 0; index--) {
|
||||
if (s.charAt(index) != '0') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return s.substring(0, index + 1);
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) {
|
||||
String stripped = StringUtils.stripStart(s, "0");
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) {
|
||||
String stripped = StringUtils.stripEnd(s, "0");
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) {
|
||||
String stripped = CharMatcher.is('0')
|
||||
.trimLeadingFrom(s);
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) {
|
||||
String stripped = CharMatcher.is('0')
|
||||
.trimTrailingFrom(s);
|
||||
|
||||
if (stripped.isEmpty() && !s.isEmpty()) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return stripped;
|
||||
}
|
||||
|
||||
public static String removeLeadingZeroesWithRegex(String s) {
|
||||
return s.replaceAll("^0+(?!$)", "");
|
||||
}
|
||||
|
||||
public static String removeTrailingZeroesWithRegex(String s) {
|
||||
return s.replaceAll("(?!^)0+$", "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.baeldung.stringduplicates;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class RemoveDuplicateFromString {
|
||||
|
||||
|
||||
String removeDuplicatesUsingCharArray(String str) {
|
||||
|
||||
char[] chars = str.toCharArray();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int repeatedCtr;
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
repeatedCtr = 0;
|
||||
for (int j = i + 1; j < chars.length; j++) {
|
||||
if (chars[i] == chars[j]) {
|
||||
repeatedCtr++;
|
||||
}
|
||||
}
|
||||
if (repeatedCtr == 0) {
|
||||
sb.append(chars[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsinglinkedHashSet(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Set<Character> linkedHashSet = new LinkedHashSet<>();
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
linkedHashSet.add(str.charAt(i));
|
||||
}
|
||||
|
||||
for (Character c : linkedHashSet) {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingSorting(String str) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if(!str.isEmpty()) {
|
||||
char[] chars = str.toCharArray();
|
||||
Arrays.sort(chars);
|
||||
|
||||
sb.append(chars[0]);
|
||||
for (int i = 1; i < chars.length; i++) {
|
||||
if (chars[i] != chars[i - 1]) {
|
||||
sb.append(chars[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingHashSet(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Set<Character> hashSet = new HashSet<>();
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
hashSet.add(str.charAt(i));
|
||||
}
|
||||
|
||||
for (Character c : hashSet) {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
String removeDuplicatesUsingIndexOf(String str) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int idx;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
idx = str.indexOf(c, i + 1);
|
||||
if (idx == -1) {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
String removeDuplicatesUsingDistinct(String str) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
str.chars().distinct().forEach(c -> sb.append((char) c));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ConvertStringToListUnitTest {
|
||||
|
||||
private final String countries = "Russia,Germany,England,France,Italy";
|
||||
private final String ranks = "1,2,3,4,5, 6,7";
|
||||
private final String emptyStrings = ",,,,,";
|
||||
private final List<String> expectedCountriesList = Arrays.asList("Russia", "Germany", "England", "France", "Italy");
|
||||
private final List<Integer> expectedRanksList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
private final List<String> expectedEmptyStringsList = Arrays.asList("", "", "", "", "", "");
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByJava() {
|
||||
List<String> convertedCountriesList = Arrays.asList(countries.split(",", -1));
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByApache() {
|
||||
List<String> convertedCountriesList = Arrays.asList(StringUtils.splitPreserveAllTokens(countries, ","));
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByGuava() {
|
||||
List<String> convertedCountriesList = Splitter.on(",")
|
||||
.trimResults()
|
||||
.splitToList(countries);
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfStringByJava8() {
|
||||
List<String> convertedCountriesList = Stream.of(countries.split(",", -1))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedCountriesList, convertedCountriesList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByJava() {
|
||||
String[] convertedRankArray = ranks.split(",");
|
||||
List<Integer> convertedRankList = new ArrayList<Integer>();
|
||||
for (String number : convertedRankArray) {
|
||||
convertedRankList.add(Integer.parseInt(number.trim()));
|
||||
}
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByGuava() {
|
||||
List<Integer> convertedRankList = Lists.transform(Splitter.on(",")
|
||||
.trimResults()
|
||||
.splitToList(ranks), new Function<String, Integer>() {
|
||||
@Override
|
||||
public Integer apply(String input) {
|
||||
return Integer.parseInt(input.trim());
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByJava8() {
|
||||
List<Integer> convertedRankList = Stream.of(ranks.split(","))
|
||||
.map(String::trim)
|
||||
.map(Integer::parseInt)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_thenGetListOfIntegerByApache() {
|
||||
String[] convertedRankArray = StringUtils.split(ranks, ",");
|
||||
List<Integer> convertedRankList = new ArrayList<Integer>();
|
||||
for (String number : convertedRankArray) {
|
||||
convertedRankList.add(Integer.parseInt(number.trim()));
|
||||
}
|
||||
|
||||
assertEquals(expectedRanksList, convertedRankList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByJava() {
|
||||
List<String> convertedEmptyStringsList = Arrays.asList(emptyStrings.split(",", -1));
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByApache() {
|
||||
List<String> convertedEmptyStringsList = Arrays.asList(StringUtils.splitPreserveAllTokens(emptyStrings, ","));
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByGuava() {
|
||||
List<String> convertedEmptyStringsList = Splitter.on(",")
|
||||
.trimResults()
|
||||
.splitToList(emptyStrings);
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStrings_thenGetListOfStringByJava8() {
|
||||
List<String> convertedEmptyStringsList = Stream.of(emptyStrings.split(",", -1))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedEmptyStringsList, convertedEmptyStringsList);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.primitives.Chars;
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.CharBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class StringFromPrimitiveArrayUnitTest {
|
||||
|
||||
private int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
|
||||
private char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
|
||||
|
||||
private char separatorChar = '-';
|
||||
|
||||
private String separator = String.valueOf(separatorChar);
|
||||
|
||||
private String expectedIntString = "1-2-3-4-5-6-7-8-9";
|
||||
|
||||
private String expectedCharString = "a-b-c-d-e-f";
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() {
|
||||
assertThat(Arrays.stream(intArray)
|
||||
.mapToObj(String::valueOf)
|
||||
.collect(Collectors.joining(separator)))
|
||||
.isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() {
|
||||
assertThat(CharBuffer.wrap(charArray).chars()
|
||||
.mapToObj(intChar -> String.valueOf((char) intChar))
|
||||
.collect(Collectors.joining(separator)))
|
||||
.isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void giveIntArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() {
|
||||
StringJoiner intStringJoiner = new StringJoiner(separator);
|
||||
|
||||
Arrays.stream(intArray)
|
||||
.mapToObj(String::valueOf)
|
||||
.forEach(intStringJoiner::add);
|
||||
|
||||
assertThat(intStringJoiner.toString()).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() {
|
||||
StringJoiner charStringJoiner = new StringJoiner(separator);
|
||||
|
||||
CharBuffer.wrap(charArray).chars()
|
||||
.mapToObj(intChar -> String.valueOf((char) intChar))
|
||||
.forEach(charStringJoiner::add);
|
||||
|
||||
assertThat(charStringJoiner.toString()).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() {
|
||||
assertThat(StringUtils.join(intArray, separatorChar)).isEqualTo(expectedIntString);
|
||||
assertThat(StringUtils.join(ArrayUtils.toObject(intArray), separator)).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() {
|
||||
assertThat(StringUtils.join(charArray, separatorChar)).isEqualTo(expectedCharString);
|
||||
assertThat(StringUtils.join(ArrayUtils.toObject(charArray), separator)).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() {
|
||||
assertThat(Joiner.on(separator).join(Ints.asList(intArray))).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() {
|
||||
assertThat(Joiner.on(separator).join(Chars.asList(charArray))).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() {
|
||||
assertThat(joinIntArrayWithStringBuilder(intArray, separator)).isEqualTo(expectedIntString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() {
|
||||
assertThat(joinCharArrayWithStringBuilder(charArray, separator)).isEqualTo(expectedCharString);
|
||||
}
|
||||
|
||||
private String joinIntArrayWithStringBuilder(int[] array, String separator) {
|
||||
if (array.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
for (int i = 0; i < array.length - 1; i++) {
|
||||
stringBuilder.append(array[i]);
|
||||
stringBuilder.append(separator);
|
||||
}
|
||||
stringBuilder.append(array[array.length - 1]);
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
private String joinCharArrayWithStringBuilder(char[] array, String separator) {
|
||||
if (array.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
for (int i = 0; i < array.length - 1; i++) {
|
||||
stringBuilder.append(array[i]);
|
||||
stringBuilder.append(separator);
|
||||
}
|
||||
stringBuilder.append(array[array.length - 1]);
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
|
||||
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));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -59,4 +59,14 @@ public class SubstringUnitTest {
|
||||
Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithLastIndexOf_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("1984", text.substring(text.lastIndexOf('-') + 1, text.indexOf('.')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithIndexOfAString_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America)", text.substring(text.indexOf("USA"), text.indexOf(')') + 1));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.string.padding;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringPaddingUtilUnitTest {
|
||||
|
||||
String inputString = "123456";
|
||||
String expectedPaddedStringSpaces = " 123456";
|
||||
String expectedPaddedStringZeros = "0000123456";
|
||||
int minPaddedStringLength = 10;
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpaces_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, StringPaddingUtil.padLeftSpaces(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpacesUsingSubstring_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, StringPaddingUtil.padLeft(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithZeros_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringZeros, StringPaddingUtil.padLeftZeros(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpacesUsingStringUtils_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, StringUtils.leftPad(inputString, minPaddedStringLength));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithZerosUsingStringUtils_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringZeros, StringUtils.leftPad(inputString, minPaddedStringLength, "0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithSpacesUsingGuavaStrings_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringSpaces, Strings.padStart(inputString, minPaddedStringLength, ' '));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenPaddingWithZerosUsingGuavaStrings_thenStringPaddedMatches() {
|
||||
assertEquals(expectedPaddedStringZeros, Strings.padStart(inputString, minPaddedStringLength, '0'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.baeldung.string.removeleadingtrailingchar;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
public class RemoveLeadingAndTrailingZeroesUnitTest {
|
||||
|
||||
public static Stream<Arguments> leadingZeroTestProvider() {
|
||||
return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("0abc", "abc"), Arguments.of("0123", "123"), Arguments.of("0000123", "123"), Arguments.of("1230", "1230"), Arguments.of("01230", "1230"), Arguments.of("01", "1"),
|
||||
Arguments.of("0001", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "12034"), Arguments.of("1203400", "1203400"));
|
||||
}
|
||||
|
||||
public static Stream<Arguments> trailingZeroTestProvider() {
|
||||
return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("abc0", "abc"), Arguments.of("1230", "123"), Arguments.of("1230000", "123"), Arguments.of("0123", "0123"), Arguments.of("01230", "0123"), Arguments.of("10", "1"),
|
||||
Arguments.of("1000", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "0012034"), Arguments.of("1203400", "12034"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithStringBuilder_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithStringBuilder(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithStringBuilder_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithStringBuilder(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithSubstring_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithSubstring(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithSubstring_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithSubstring(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithApacheCommonsStripStart_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithApacheCommonsStripStart(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithApacheCommonsStripEnd_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithApacheCommonsStripEnd(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithGuavaTrimLeadingFrom_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithGuavaTrimLeadingFrom(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithGuavaTrimTrailingFrom_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithGuavaTrimTrailingFrom(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("leadingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveLeadingZeroesWithRegex_thenReturnWithoutLeadingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithRegex(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("trailingZeroTestProvider")
|
||||
public void givenTestStrings_whenRemoveTrailingZeroesWithRegex_thenReturnWithoutTrailingZeroes(String input, String expected) {
|
||||
// given
|
||||
|
||||
// when
|
||||
String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithRegex(input);
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.stringduplicates;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RemoveDuplicateFromStringUnitTest {
|
||||
|
||||
private final static String STR1 = "racecar";
|
||||
private final static String STR2 = "J2ee programming";
|
||||
private final static String STR_EMPTY = "";
|
||||
|
||||
private RemoveDuplicateFromString removeDuplicateFromString;
|
||||
|
||||
@Before
|
||||
public void executedBeforeEach() {
|
||||
removeDuplicateFromString = new RemoveDuplicateFromString();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenUsingCharArray_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("ecar", str1);
|
||||
Assert.assertEquals("J2e poraming", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingLinkedHashSet_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR2);
|
||||
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("race", str1);
|
||||
Assert.assertEquals("J2e progamin", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSorting_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR2);
|
||||
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingSorting(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("acer", str1);
|
||||
Assert.assertEquals(" 2Jaegimnopr", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHashSet_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("arce", str1);
|
||||
Assert.assertEquals(" pa2regiJmno", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingIndexOf_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("ecar", str1);
|
||||
Assert.assertEquals("J2e poraming", str2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJava8_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
|
||||
String str1 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR1);
|
||||
String str2 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR2);
|
||||
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR_EMPTY);
|
||||
Assert.assertEquals("", strEmpty);
|
||||
Assert.assertEquals("race", str1);
|
||||
Assert.assertEquals("J2e progamin", str2);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user