[BAEL-12899] - Splitted the java-strings module (#7410)
This commit is contained in:
committed by
Josh Cummings
parent
87ba90d455
commit
ec46f6de26
22
java-strings-ops/README.md
Normal file
22
java-strings-ops/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
=========
|
||||
|
||||
## Java Strings Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
||||
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||
- [Java String Conversions](https://www.baeldung.com/java-string-conversions)
|
||||
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
|
||||
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
|
||||
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
|
||||
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
|
||||
- [How to Remove the Last Character of a String?](http://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)
|
||||
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
|
||||
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
|
||||
- [Split a String in Java](http://www.baeldung.com/java-split-string)
|
||||
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
|
||||
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
|
||||
- [Java toString() Method](https://www.baeldung.com/java-tostring)
|
||||
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
|
||||
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
|
||||
99
java-strings-ops/pom.xml
Normal file
99
java-strings-ops/pom.xml
Normal file
@@ -0,0 +1,99 @@
|
||||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-strings-ops</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>java-strings-ops</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>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</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-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter-api.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-strings-ops</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class UseLocalDateTime {
|
||||
|
||||
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
|
||||
return LocalDateTime.parse(representation);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionX {
|
||||
|
||||
public String addCharUsingCharArray(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
int len = str.length();
|
||||
char[] updatedArr = new char[len + 1];
|
||||
str.getChars(0, position, updatedArr, 0);
|
||||
updatedArr[position] = ch;
|
||||
str.getChars(position, len, updatedArr, position + 1);
|
||||
return new String(updatedArr);
|
||||
}
|
||||
|
||||
public String addCharUsingSubstring(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
return str.substring(0, position) + ch + str.substring(position);
|
||||
}
|
||||
|
||||
public String addCharUsingStringBuilder(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
StringBuilder sb = new StringBuilder(str);
|
||||
sb.insert(position, ch);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void validate(String str, int position) {
|
||||
if (str == null) {
|
||||
throw new IllegalArgumentException("Str should not be null");
|
||||
}
|
||||
int len = str.length();
|
||||
if (position < 0 || position > len) {
|
||||
throw new IllegalArgumentException("position[" + position + "] should be "
|
||||
+ "in the range 0.." + len + " for string " + str);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class Palindrome {
|
||||
|
||||
public boolean isPalindrome(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
int length = clean.length();
|
||||
int forward = 0;
|
||||
int backward = length - 1;
|
||||
while (backward > forward) {
|
||||
char forwardChar = clean.charAt(forward++);
|
||||
char backwardChar = clean.charAt(backward--);
|
||||
if (forwardChar != backwardChar)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isPalindromeReverseTheString(String text) {
|
||||
StringBuilder reverse = new StringBuilder();
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
char[] plain = clean.toCharArray();
|
||||
for (int i = plain.length - 1; i >= 0; i--)
|
||||
reverse.append(plain[i]);
|
||||
return (reverse.toString()).equals(clean);
|
||||
}
|
||||
|
||||
public boolean isPalindromeUsingStringBuilder(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
StringBuilder plain = new StringBuilder(clean);
|
||||
StringBuilder reverse = plain.reverse();
|
||||
return (reverse.toString()).equals(clean);
|
||||
}
|
||||
|
||||
public boolean isPalindromeUsingStringBuffer(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
StringBuffer plain = new StringBuffer(clean);
|
||||
StringBuffer reverse = plain.reverse();
|
||||
return (reverse.toString()).equals(clean);
|
||||
}
|
||||
|
||||
public boolean isPalindromeRecursive(String text) {
|
||||
String clean = text.replaceAll("\\s+", "").toLowerCase();
|
||||
return recursivePalindrome(clean, 0, clean.length() - 1);
|
||||
}
|
||||
|
||||
private boolean recursivePalindrome(String text, int forward, int backward) {
|
||||
if (forward == backward)
|
||||
return true;
|
||||
if ((text.charAt(forward)) != (text.charAt(backward)))
|
||||
return false;
|
||||
if (forward < backward + 1) {
|
||||
return recursivePalindrome(text, forward + 1, backward - 1);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isPalindromeUsingIntStream(String text) {
|
||||
String temp = text.replaceAll("\\s+", "").toLowerCase();
|
||||
return IntStream.range(0, temp.length() / 2)
|
||||
.noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
class StringHelper {
|
||||
static String removeLastChar(String s) {
|
||||
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
|
||||
}
|
||||
|
||||
static String removeLastCharRegex(String s) {
|
||||
return (s == null) ? s : s.replaceAll(".$", "");
|
||||
}
|
||||
|
||||
static String removeLastCharOptional(String s) {
|
||||
return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s);
|
||||
}
|
||||
|
||||
static String removeLastCharRegexOptional(String s) {
|
||||
return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class Customer {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CustomerArrayToString extends Customer {
|
||||
private Order[] orders;
|
||||
|
||||
public Order[] getOrders() {
|
||||
return orders;
|
||||
}
|
||||
public void setOrders(Order[] orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName()
|
||||
+ ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class CustomerComplexObjectToString extends Customer {
|
||||
private Order order;
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(Order order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [order=" + order + ", getFirstName()=" + getFirstName()
|
||||
+ ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class CustomerPrimitiveToString extends Customer {
|
||||
private long balance;
|
||||
|
||||
public long getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(long balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName()
|
||||
+ ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
public class CustomerReflectionToString extends Customer{
|
||||
|
||||
private Integer score;
|
||||
private List<String> orders;
|
||||
private StringBuffer fullname;
|
||||
|
||||
public Integer getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(Integer score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public List<String> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(List<String> orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
public StringBuffer getFullname() {
|
||||
return fullname;
|
||||
}
|
||||
|
||||
public void setFullname(StringBuffer fullname) {
|
||||
this.fullname = fullname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class CustomerWrapperCollectionToString extends Customer {
|
||||
private Integer score;
|
||||
private List<String> orders;
|
||||
private StringBuffer fullname;
|
||||
|
||||
public Integer getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(Integer score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public List<String> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(List<String> orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
public StringBuffer getFullname() {
|
||||
return fullname;
|
||||
}
|
||||
|
||||
public void setFullname(StringBuffer fullname) {
|
||||
this.fullname = fullname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname
|
||||
+ ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
public class Order {
|
||||
|
||||
private String orderId;
|
||||
private String desc;
|
||||
private long value;
|
||||
private String status;
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public long getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(long value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]";
|
||||
}
|
||||
|
||||
}
|
||||
13
java-strings-ops/src/main/resources/logback.xml
Normal file
13
java-strings-ops/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class CharToStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
|
||||
final char givenChar = 'x';
|
||||
|
||||
final String result = String.valueOf(givenChar);
|
||||
|
||||
assertThat(result).isEqualTo("x");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() {
|
||||
final char givenChar = 'x';
|
||||
|
||||
final String result = Character.toString(givenChar);
|
||||
|
||||
assertThat(result).isEqualTo("x");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3() {
|
||||
final char givenChar = 'x';
|
||||
|
||||
final String result = new Character(givenChar).toString();
|
||||
|
||||
assertThat(result).isEqualTo("x");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenChar_whenConcatenated_shouldConvertToString4() {
|
||||
final char givenChar = 'x';
|
||||
|
||||
final String result = givenChar + "";
|
||||
|
||||
assertThat(result).isEqualTo("x");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenChar_whenFormated_shouldConvertToString5() {
|
||||
final char givenChar = 'x';
|
||||
|
||||
final String result = String.format("%c", givenChar);
|
||||
|
||||
assertThat(result).isEqualTo("x");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
Relevant Articles:
|
||||
- [Java String Conversions](http://www.baeldung.com/java-string-conversions)
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.java.conversion;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetime.UseLocalDateTime;
|
||||
|
||||
public class StringConversionUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenConvertedToInt_thenCorrect() {
|
||||
String beforeConvStr = "1";
|
||||
int afterConvInt = 1;
|
||||
|
||||
assertEquals(Integer.parseInt(beforeConvStr), afterConvInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToInteger_thenCorrect() {
|
||||
String beforeConvStr = "12";
|
||||
Integer afterConvInteger = 12;
|
||||
|
||||
assertEquals(Integer.valueOf(beforeConvStr).equals(afterConvInteger), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedTolong_thenCorrect() {
|
||||
String beforeConvStr = "12345";
|
||||
long afterConvLongPrimitive = 12345;
|
||||
|
||||
assertEquals(Long.parseLong(beforeConvStr), afterConvLongPrimitive);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToLong_thenCorrect() {
|
||||
String beforeConvStr = "14567";
|
||||
Long afterConvLong = 14567l;
|
||||
|
||||
assertEquals(Long.valueOf(beforeConvStr).equals(afterConvLong), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedTodouble_thenCorrect() {
|
||||
String beforeConvStr = "1.4";
|
||||
double afterConvDoublePrimitive = 1.4;
|
||||
|
||||
assertEquals(Double.parseDouble(beforeConvStr), afterConvDoublePrimitive, 0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToDouble_thenCorrect() {
|
||||
String beforeConvStr = "145.67";
|
||||
double afterConvDouble = 145.67d;
|
||||
|
||||
assertEquals(Double.valueOf(beforeConvStr).equals(afterConvDouble), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToByteArr_thenCorrect() {
|
||||
String beforeConvStr = "abc";
|
||||
byte[] afterConvByteArr = new byte[] { 'a', 'b', 'c' };
|
||||
|
||||
assertEquals(Arrays.equals(beforeConvStr.getBytes(), afterConvByteArr), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToboolean_thenCorrect() {
|
||||
String beforeConvStr = "true";
|
||||
boolean afterConvBooleanPrimitive = true;
|
||||
|
||||
assertEquals(Boolean.parseBoolean(beforeConvStr), afterConvBooleanPrimitive);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToBoolean_thenCorrect() {
|
||||
String beforeConvStr = "true";
|
||||
Boolean afterConvBoolean = true;
|
||||
|
||||
assertEquals(Boolean.valueOf(beforeConvStr), afterConvBoolean);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToCharArr_thenCorrect() {
|
||||
String beforeConvStr = "hello";
|
||||
char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' };
|
||||
|
||||
assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToDate_thenCorrect() throws ParseException {
|
||||
String beforeConvStr = "15/10/2013";
|
||||
int afterConvCalendarDay = 15;
|
||||
int afterConvCalendarMonth = 9;
|
||||
int afterConvCalendarYear = 2013;
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy");
|
||||
Date afterConvDate = formatter.parse(beforeConvStr);
|
||||
Calendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(afterConvDate);
|
||||
|
||||
assertEquals(calendar.get(Calendar.DAY_OF_MONTH), afterConvCalendarDay);
|
||||
assertEquals(calendar.get(Calendar.MONTH), afterConvCalendarMonth);
|
||||
assertEquals(calendar.get(Calendar.YEAR), afterConvCalendarYear);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToLocalDateTime_thenCorrect() {
|
||||
String str = "2007-12-03T10:15:30";
|
||||
int afterConvCalendarDay = 03;
|
||||
Month afterConvCalendarMonth = Month.DECEMBER;
|
||||
int afterConvCalendarYear = 2007;
|
||||
LocalDateTime afterConvDate = new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
|
||||
|
||||
assertEquals(afterConvDate.getDayOfMonth(), afterConvCalendarDay);
|
||||
assertEquals(afterConvDate.getMonth(), afterConvCalendarMonth);
|
||||
assertEquals(afterConvDate.getYear(), afterConvCalendarYear);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.java.countingChars;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
|
||||
|
||||
/***
|
||||
* Example of counting chars in a String.
|
||||
*/
|
||||
public class CountCharsExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingLoop_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
char someChar = 'e';
|
||||
int count = 0;
|
||||
for (int i = 0; i < someString.length(); i++) {
|
||||
if (someString.charAt(i) == someChar) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingReplace_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
int count = someString.length() - someString.replace("e", "").length();
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingSplit_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
int count = someString.split("e", -1).length - 1;
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingReqExp_thenCountChars() {
|
||||
Pattern pattern = Pattern.compile("[^e]*e");
|
||||
Matcher matcher = pattern.matcher("elephant");
|
||||
int count = 0;
|
||||
while (matcher.find()) {
|
||||
count++;
|
||||
}
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingRecursion_thenCountChars() {
|
||||
int count = useRecursion("elephant", 'e', 0);
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
private int useRecursion(String someString, char searchedChar, int index) {
|
||||
if (index >= someString.length()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int count = someString.charAt(index) == searchedChar ? 1 : 0;
|
||||
return count + useRecursion(someString, searchedChar, index + 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingStringUtils_thenCountChars() throws InterruptedException {
|
||||
int count = StringUtils.countMatches("elephant", "e");
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingJava8Features_thenCountChars() {
|
||||
String someString = "elephant";
|
||||
long count = someString.chars().filter(ch -> ch == 'e').count();
|
||||
assertEquals(2, count);
|
||||
|
||||
long count2 = someString.codePoints().filter(ch -> ch == 'e').count();
|
||||
assertEquals(2, count2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingGuavaCharMatcher_thenCountChars() {
|
||||
int count = CharMatcher.is('e').countIn("elephant");
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionXUnitTest {
|
||||
|
||||
private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
|
||||
private String word = "Titanc";
|
||||
private char letter = 'i';
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CharSequenceVsStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUsingString_whenInstantiatingString_thenWrong() {
|
||||
CharSequence firstString = "bealdung";
|
||||
String secondString = "baeldung";
|
||||
|
||||
assertNotEquals(firstString, secondString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalCharSequences_whenCastToString_thenEqual() {
|
||||
CharSequence charSequence1 = "baeldung_1";
|
||||
CharSequence charSequence2 = "baeldung_2";
|
||||
|
||||
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenAppended_thenUnmodified() {
|
||||
String test = "a";
|
||||
int firstAddressOfTest = System.identityHashCode(test);
|
||||
test += "b";
|
||||
int secondAddressOfTest = System.identityHashCode(test);
|
||||
|
||||
assertNotEquals(firstAddressOfTest, secondAddressOfTest);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringBuilder_whenAppended_thenModified() {
|
||||
StringBuilder test = new StringBuilder();
|
||||
test.append("a");
|
||||
int firstAddressOfTest = System.identityHashCode(test);
|
||||
test.append("b");
|
||||
int secondAddressOfTest = System.identityHashCode(test);
|
||||
|
||||
assertEquals(firstAddressOfTest, secondAddressOfTest);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PalindromeUnitTest {
|
||||
|
||||
private String[] words = {
|
||||
"Anna",
|
||||
"Civic",
|
||||
"Kayak",
|
||||
"Level",
|
||||
"Madam",
|
||||
};
|
||||
|
||||
private String[] sentences = {
|
||||
"Sore was I ere I saw Eros",
|
||||
"Euston saw I was not Sue",
|
||||
"Too hot to hoot",
|
||||
"No mists or frost Simon",
|
||||
"Stella won no wallets"
|
||||
};
|
||||
|
||||
private Palindrome palindrome = new Palindrome();
|
||||
|
||||
@Test
|
||||
public void whenWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindrome(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindrome(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeReverseTheString(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeReverseTheString(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuilderWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuilder(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuilderSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBufferWord_shouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuffer(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBufferSentence_shouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeRecursive_wordShouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeRecursive(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeRecursive_sentenceShouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeRecursive(sentence));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeStreams_wordShouldBePalindrome() {
|
||||
for (String word : words)
|
||||
assertTrue(palindrome.isPalindromeUsingIntStream(word));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPalindromeStreams_sentenceShouldBePalindrome() {
|
||||
for (String sentence : sentences)
|
||||
assertTrue(palindrome.isPalindromeUsingIntStream(sentence));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
|
||||
public class SplitUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenSplit_thenReturnsArray_through_JavaLangString() {
|
||||
assertThat("peter,james,thomas".split(","))
|
||||
.containsExactly("peter", "james", "thomas");
|
||||
|
||||
assertThat("car jeep scooter".split(" "))
|
||||
.containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat("1-120-232323".split("-"))
|
||||
.containsExactly("1", "120", "232323");
|
||||
|
||||
assertThat("192.168.1.178".split("\\."))
|
||||
.containsExactly("192", "168", "1", "178");
|
||||
|
||||
assertThat("b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*"))
|
||||
.containsExactly("b", "a", "e", "l", "d", "u", "n", "g");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSplit_thenReturnsArray_through_StringUtils() {
|
||||
StringUtils.split("car jeep scooter");
|
||||
|
||||
assertThat(StringUtils.split("car jeep scooter"))
|
||||
.containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat(StringUtils.split("car jeep scooter"))
|
||||
.containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat(StringUtils.split("car:jeep:scooter", ":"))
|
||||
.containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat(StringUtils.split("car.jeep.scooter", "."))
|
||||
.containsExactly("car", "jeep", "scooter");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSplit_thenReturnsList_Splitter() {
|
||||
//given
|
||||
List<String> resultList = Splitter.on(',').trimResults().omitEmptyStrings().splitToList("car,jeep,, scooter");
|
||||
|
||||
assertThat(resultList)
|
||||
.containsExactly("car", "jeep", "scooter");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_Regex() {
|
||||
assertThat(" car , jeep, scooter ".trim()
|
||||
.split("\\s*,\\s*")).containsExactly("car", "jeep", "scooter");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_java_8() {
|
||||
assertThat(Arrays.stream(" car , jeep, scooter ".split(","))
|
||||
.map(String::trim)
|
||||
.toArray(String[]::new)).containsExactly("car", "jeep", "scooter");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class StringBufferStringBuilder {
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(StringBufferStringBuilder.class.getSimpleName())
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class MyState {
|
||||
int iterations = 1000;
|
||||
String initial = "abc";
|
||||
String suffix = "def";
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public StringBuffer benchmarkStringBuffer(MyState state) {
|
||||
StringBuffer stringBuffer = new StringBuffer(state.initial);
|
||||
for (int i = 0; i < state.iterations; i++) {
|
||||
stringBuffer.append(state.suffix);
|
||||
}
|
||||
return stringBuffer;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public StringBuilder benchmarkStringBuilder(MyState state) {
|
||||
StringBuilder stringBuilder = new StringBuilder(state.initial);
|
||||
for (int i = 0; i < state.iterations; i++) {
|
||||
stringBuilder.append(state.suffix);
|
||||
}
|
||||
return stringBuilder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringComparisonUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingComparisonOperator_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using comparison operator";
|
||||
String string2 = "using comparison operator";
|
||||
String string3 = new String("using comparison operator");
|
||||
|
||||
assertThat(string1 == string2).isTrue();
|
||||
assertThat(string1 == string3).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsMethod_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using equals method";
|
||||
String string2 = "using equals method";
|
||||
|
||||
String string3 = "using EQUALS method";
|
||||
String string4 = new String("using equals method");
|
||||
|
||||
assertThat(string1.equals(string2)).isTrue();
|
||||
assertThat(string1.equals(string4)).isTrue();
|
||||
|
||||
assertThat(string1.equals(null)).isFalse();
|
||||
assertThat(string1.equals(string3)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsIgnoreCase_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using equals ignore case";
|
||||
String string2 = "USING EQUALS IGNORE CASE";
|
||||
|
||||
assertThat(string1.equalsIgnoreCase(string2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareTo_ThenComparingStrings(){
|
||||
|
||||
String author = "author";
|
||||
String book = "book";
|
||||
String duplicateBook = "book";
|
||||
|
||||
assertThat(author.compareTo(book)).isEqualTo(-1);
|
||||
assertThat(book.compareTo(author)).isEqualTo(1);
|
||||
assertThat(duplicateBook.compareTo(book)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareToIgnoreCase_ThenComparingStrings(){
|
||||
|
||||
String author = "Author";
|
||||
String book = "book";
|
||||
String duplicateBook = "BOOK";
|
||||
|
||||
assertThat(author.compareToIgnoreCase(book)).isEqualTo(-1);
|
||||
assertThat(book.compareToIgnoreCase(author)).isEqualTo(1);
|
||||
assertThat(duplicateBook.compareToIgnoreCase(book)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingObjectsEqualsMethod_ThenComparingStrings(){
|
||||
|
||||
String string1 = "using objects equals";
|
||||
String string2 = "using objects equals";
|
||||
String string3 = new String("using objects equals");
|
||||
|
||||
assertThat(Objects.equals(string1, string2)).isTrue();
|
||||
assertThat(Objects.equals(string1, string3)).isTrue();
|
||||
|
||||
assertThat(Objects.equals(null, null)).isTrue();
|
||||
assertThat(Objects.equals(null, string1)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsOfApacheCommons_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equals(null, null)).isTrue();
|
||||
assertThat(StringUtils.equals(null, "equals method")).isFalse();
|
||||
assertThat(StringUtils.equals("equals method", "equals method")).isTrue();
|
||||
assertThat(StringUtils.equals("equals method", "EQUALS METHOD")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse();
|
||||
assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method")).isTrue();
|
||||
assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsAnyOf_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equalsAny(null, null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue();
|
||||
assertThat(StringUtils.equalsAny("equals any", null, "equals any")).isTrue();
|
||||
assertThat(StringUtils.equalsAny(null, "equals", "any")).isFalse();
|
||||
assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(
|
||||
"equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompare_thenComparingStringsWithNulls(){
|
||||
|
||||
assertThat(StringUtils.compare(null, null)).isEqualTo(0);
|
||||
assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1);
|
||||
|
||||
assertThat(StringUtils.compare("abc", "bbc")).isEqualTo(-1);
|
||||
assertThat(StringUtils.compare("bbc", "abc")).isEqualTo(1);
|
||||
assertThat(StringUtils.compare("abc", "abc")).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls(){
|
||||
|
||||
assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0);
|
||||
assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1);
|
||||
|
||||
assertThat(StringUtils.compareIgnoreCase("Abc", "bbc")).isEqualTo(-1);
|
||||
assertThat(StringUtils.compareIgnoreCase("bbc", "ABC")).isEqualTo(1);
|
||||
assertThat(StringUtils.compareIgnoreCase("abc", "ABC")).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings(){
|
||||
|
||||
assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1);
|
||||
assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class StringHelperUnitTest {
|
||||
|
||||
public static final String TEST_STRING = "abcdef";
|
||||
public static final String NULL_STRING = null;
|
||||
public static final String EMPTY_STRING = "";
|
||||
public static final String ONE_CHAR_STRING = "a";
|
||||
public static final String WHITE_SPACE_AT_THE_END_STRING = "abc ";
|
||||
public static final String NEW_LINE_AT_THE_END_STRING = "abc\n";
|
||||
public static final String MULTIPLE_LINES_STRING = "abc\ndef";
|
||||
|
||||
@Test
|
||||
public void givenTestString_whenSubstring_thenGetStingWithoutLastChar() {
|
||||
assertEquals("abcde", StringHelper.removeLastChar(TEST_STRING));
|
||||
assertEquals("abcde", StringUtils.substring(TEST_STRING, 0, TEST_STRING.length() - 1));
|
||||
assertEquals("abcde", StringUtils.chop(TEST_STRING));
|
||||
assertEquals("abcde", TEST_STRING.replaceAll(".$", ""));
|
||||
assertEquals("abcde", StringHelper.removeLastCharRegex(TEST_STRING));
|
||||
assertEquals("abcde", StringHelper.removeLastCharOptional(TEST_STRING));
|
||||
assertEquals("abcde", StringHelper.removeLastCharRegexOptional(TEST_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullString_whenSubstring_thenGetNullString() {
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastChar(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringUtils.chop(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastCharRegex(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastCharOptional(NULL_STRING));
|
||||
assertEquals(NULL_STRING, StringHelper.removeLastCharRegexOptional(NULL_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenSubstring_thenGetEmptyString() {
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastChar(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, StringUtils.substring(EMPTY_STRING, 0, EMPTY_STRING.length() - 1));
|
||||
assertEquals(EMPTY_STRING, StringUtils.chop(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, EMPTY_STRING.replaceAll(".$", ""));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegex(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharOptional(EMPTY_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegexOptional(EMPTY_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneCharString_whenSubstring_thenGetEmptyString() {
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastChar(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, StringUtils.substring(ONE_CHAR_STRING, 0, ONE_CHAR_STRING.length() - 1));
|
||||
assertEquals(EMPTY_STRING, StringUtils.chop(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, ONE_CHAR_STRING.replaceAll(".$", ""));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegex(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharOptional(ONE_CHAR_STRING));
|
||||
assertEquals(EMPTY_STRING, StringHelper.removeLastCharRegexOptional(ONE_CHAR_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringWithWhiteSpaceAtTheEnd_whenSubstring_thenGetStringWithoutWhiteSpaceAtTheEnd() {
|
||||
assertEquals("abc", StringHelper.removeLastChar(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringUtils.substring(WHITE_SPACE_AT_THE_END_STRING, 0, WHITE_SPACE_AT_THE_END_STRING.length() - 1));
|
||||
assertEquals("abc", StringUtils.chop(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", WHITE_SPACE_AT_THE_END_STRING.replaceAll(".$", ""));
|
||||
assertEquals("abc", StringHelper.removeLastCharRegex(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringHelper.removeLastCharOptional(WHITE_SPACE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringHelper.removeLastCharRegexOptional(WHITE_SPACE_AT_THE_END_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringWithNewLineAtTheEnd_whenSubstring_thenGetStringWithoutNewLine() {
|
||||
assertEquals("abc", StringHelper.removeLastChar(NEW_LINE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringUtils.substring(NEW_LINE_AT_THE_END_STRING, 0, NEW_LINE_AT_THE_END_STRING.length() - 1));
|
||||
assertEquals("abc", StringUtils.chop(NEW_LINE_AT_THE_END_STRING));
|
||||
assertNotEquals("abc", NEW_LINE_AT_THE_END_STRING.replaceAll(".$", ""));
|
||||
assertNotEquals("abc", StringHelper.removeLastCharRegex(NEW_LINE_AT_THE_END_STRING));
|
||||
assertEquals("abc", StringHelper.removeLastCharOptional(NEW_LINE_AT_THE_END_STRING));
|
||||
assertNotEquals("abc", StringHelper.removeLastCharRegexOptional(NEW_LINE_AT_THE_END_STRING));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiLineString_whenSubstring_thenGetStringWithoutNewLine() {
|
||||
assertEquals("abc\nde", StringHelper.removeLastChar(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", StringUtils.substring(MULTIPLE_LINES_STRING, 0, MULTIPLE_LINES_STRING.length() - 1));
|
||||
assertEquals("abc\nde", StringUtils.chop(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", MULTIPLE_LINES_STRING.replaceAll(".$", ""));
|
||||
assertEquals("abc\nde", StringHelper.removeLastCharRegex(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", StringHelper.removeLastCharOptional(MULTIPLE_LINES_STRING));
|
||||
assertEquals("abc\nde", StringHelper.removeLastCharRegexOptional(MULTIPLE_LINES_STRING));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SubstringUnitTest {
|
||||
|
||||
String text = "Julia Evans was born on 25-09-1984. She is currently living in the USA (United States of America).";
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedStringUtils_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("United States of America", StringUtils.substringBetween(text, "(", ")"));
|
||||
Assert.assertEquals("the USA (United States of America).", StringUtils.substringAfter(text, "living in "));
|
||||
Assert.assertEquals("Julia Evans", StringUtils.substringBefore(text, " was born"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedScanner_ShouldReturnProperSubstring() {
|
||||
try (Scanner scanner = new Scanner(text)) {
|
||||
scanner.useDelimiter("\\.");
|
||||
Assert.assertEquals("Julia Evans was born on 25-09-1984", scanner.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSplit_ShouldReturnProperSubstring() {
|
||||
String[] sentences = text.split("\\.");
|
||||
Assert.assertEquals("Julia Evans was born on 25-09-1984", sentences[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedRegex_ShouldReturnProperSubstring() {
|
||||
Pattern pattern = Pattern.compile("\\d{2}\\-\\d{2}-\\d{4}");
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
if (matcher.find()) {
|
||||
Assert.assertEquals("25-09-1984", matcher.group());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubSequence_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America)", text.subSequence(67, text.length() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstring_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America).", text.substring(67));
|
||||
Assert.assertEquals("USA (United States of America)", text.substring(67, text.length() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithIndexOf_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithLastIndexOf_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("1984", text.substring(text.lastIndexOf('-') + 1, text.indexOf('.')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithIndexOfAString_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America)", text.substring(text.indexOf("USA"), text.indexOf(')') + 1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.string.conversion;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ByteArrayToStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithDefaultCharset_thenOK() {
|
||||
final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114,
|
||||
108, 100, 33 };
|
||||
String string = new String(byteArrray);
|
||||
System.out.println(string);
|
||||
|
||||
assertNotNull(string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithNamedCharset_thenOK()
|
||||
throws UnsupportedEncodingException {
|
||||
final String charsetName = "IBM01140";
|
||||
final byte[] byteArrray = { -56, -123, -109, -109, -106, 64, -26, -106,
|
||||
-103, -109, -124, 90 };
|
||||
|
||||
String string = new String(byteArrray, charsetName);
|
||||
|
||||
assertEquals("Hello World!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithCharSet_thenOK() {
|
||||
final Charset charset = Charset.forName("UTF-8");
|
||||
final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114,
|
||||
108, 100, 33 };
|
||||
|
||||
String string = new String(byteArrray, charset);
|
||||
|
||||
assertEquals("Hello World!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringConstructorWithStandardCharSet_thenOK() {
|
||||
final Charset charset = StandardCharsets.UTF_16;
|
||||
|
||||
final byte[] byteArrray = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0,
|
||||
111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 };
|
||||
|
||||
String string = new String(byteArrray, charset);
|
||||
|
||||
assertEquals("Hello World!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDecodeWithCharset_thenOK() {
|
||||
byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33 };
|
||||
final Charset charset = StandardCharsets.US_ASCII;
|
||||
|
||||
String string = charset.decode(ByteBuffer.wrap(byteArrray)).toString();
|
||||
System.out.println(string);
|
||||
|
||||
assertEquals("Hello <20>orl<72>!", string);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharsetDecoder_thenOK()
|
||||
throws CharacterCodingException {
|
||||
byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33};
|
||||
CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();
|
||||
|
||||
decoder.onMalformedInput(CodingErrorAction.REPLACE)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPLACE)
|
||||
.replaceWith("?");
|
||||
|
||||
String string = decoder.decode(ByteBuffer.wrap(byteArrray)).toString();
|
||||
|
||||
assertEquals("Hello ?orl?!", string);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.baeldung.string.conversion;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetEncoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringToByteArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithDefaultCharset_thenOK() {
|
||||
final String inputString = "Hello World!";
|
||||
final String defaultCharSet = Charset.defaultCharset()
|
||||
.displayName();
|
||||
|
||||
byte[] byteArrray = inputString.getBytes();
|
||||
|
||||
System.out.printf(
|
||||
"Using default charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
defaultCharSet, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertNotNull(byteArrray);
|
||||
assert (byteArrray.length >= inputString.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithNamedCharset_thenOK()
|
||||
throws UnsupportedEncodingException {
|
||||
final String inputString = "Hello World!";
|
||||
final String charsetName = "IBM01140";
|
||||
|
||||
byte[] byteArrray = inputString.getBytes("IBM01140");
|
||||
|
||||
System.out.printf(
|
||||
"Using named charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charsetName, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(new byte[] { -56, -123, -109, -109, -106, 64, -26,
|
||||
-106, -103, -109, -124, 90 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithCharset_thenOK() {
|
||||
final String inputString = "Hello ਸੰਸਾਰ!";
|
||||
final Charset charset = Charset.forName("ASCII");
|
||||
|
||||
byte[] byteArrray = inputString.getBytes(charset);
|
||||
|
||||
System.out.printf(
|
||||
"Using Charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charset, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(
|
||||
new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBytesWithStandardCharset_thenOK() {
|
||||
final String inputString = "Hello World!";
|
||||
final Charset charset = StandardCharsets.UTF_16;
|
||||
|
||||
byte[] byteArrray = inputString.getBytes(charset);
|
||||
|
||||
System.out.printf(
|
||||
"Using Standard Charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charset, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0,
|
||||
111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEncodeWithCharset_thenOK() {
|
||||
final String inputString = "Hello ਸੰਸਾਰ!";
|
||||
final Charset charset = StandardCharsets.US_ASCII;
|
||||
|
||||
byte[] byteArrray = charset.encode(inputString)
|
||||
.array();
|
||||
|
||||
System.out.printf(
|
||||
"Using encode with Charset:%s, Input String:%s, Output byte array:%s\n",
|
||||
charset, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(
|
||||
new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharsetEncoder_thenOK()
|
||||
throws CharacterCodingException {
|
||||
final String inputString = "Hello ਸੰਸਾਰ!";
|
||||
CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();
|
||||
encoder.onMalformedInput(CodingErrorAction.IGNORE)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPLACE)
|
||||
.replaceWith(new byte[] { 0 });
|
||||
|
||||
byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString))
|
||||
.array();
|
||||
|
||||
System.out.printf(
|
||||
"Using encode with CharsetEncoder:%s, Input String:%s, Output byte array:%s\n",
|
||||
encoder, inputString, Arrays.toString(byteArrray));
|
||||
|
||||
assertArrayEquals(
|
||||
new byte[] { 72, 101, 108, 108, 111, 32, 0, 0, 0, 0, 0, 33 },
|
||||
byteArrray);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerArrayToStringUnitTest {
|
||||
private static final String CUSTOMER_ARRAY_TO_STRING
|
||||
= "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenArray_whenToString_thenCustomerDetails() {
|
||||
CustomerArrayToString customer = new CustomerArrayToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
Order[] orders = new Order[1];
|
||||
orders[0] = new Order();
|
||||
orders[0].setOrderId("A1111");
|
||||
orders[0].setDesc("Game");
|
||||
orders[0].setStatus("In-Shiping");
|
||||
customer.setOrders(orders);
|
||||
|
||||
assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerComplexObjectToStringUnitTest {
|
||||
private static final String CUSTOMER_COMPLEX_TO_STRING
|
||||
= "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenComplex_whenToString_thenCustomerDetails() {
|
||||
CustomerComplexObjectToString customer = new CustomerComplexObjectToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
Order order = new Order();
|
||||
order.setOrderId("A1111");
|
||||
order.setDesc("Game");
|
||||
order.setStatus("In-Shiping");
|
||||
customer.setOrder(order);
|
||||
|
||||
assertEquals(CUSTOMER_COMPLEX_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerPrimitiveToStringUnitTest {
|
||||
|
||||
private static final String CUSTOMER_PRIMITIVE_TO_STRING
|
||||
= "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenPrimitive_whenToString_thenCustomerDetails() {
|
||||
CustomerPrimitiveToString customer = new CustomerPrimitiveToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
customer.setBalance(110);
|
||||
|
||||
assertEquals(CUSTOMER_PRIMITIVE_TO_STRING, customer.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.string.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerWrapperCollectionToStringUnitTest {
|
||||
private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING
|
||||
= "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() {
|
||||
CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
customer.setScore(8);
|
||||
|
||||
List<String> orders = new ArrayList<String>();
|
||||
orders.add("Book");
|
||||
orders.add("Pen");
|
||||
customer.setOrders(orders);
|
||||
|
||||
StringBuffer fullname = new StringBuffer();
|
||||
fullname.append(customer.getLastName()+", "+ customer.getFirstName());
|
||||
customer.setFullname(fullname);
|
||||
|
||||
assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CoreJavaIsNumericUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCoreJava_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(isNumeric("22")).isTrue();
|
||||
assertThat(isNumeric("5.05")).isTrue();
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
assertThat(isNumeric("10.0d")).isTrue();
|
||||
assertThat(isNumeric(" 22 ")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric(null)).isFalse();
|
||||
assertThat(isNumeric("")).isFalse();
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.stringpool;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class StringPoolUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingConstantStrings_thenTheirAddressesAreEqual() {
|
||||
String constantString1 = "Baeldung";
|
||||
String constantString2 = "Baeldung";
|
||||
|
||||
assertThat(constantString1).isSameAs(constantString2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingStringsWithTheNewOperator_thenTheirAddressesAreDifferent() {
|
||||
String newString1 = new String("Baeldung");
|
||||
String newString2 = new String("Baeldung");
|
||||
|
||||
assertThat(newString1).isNotSameAs(newString2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingConstantAndNewStrings_thenTheirAddressesAreDifferent() {
|
||||
String constantString = "Baeldung";
|
||||
String newString = new String("Baeldung");
|
||||
|
||||
assertThat(constantString).isNotSameAs(newString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInterningAStringWithIdenticalValueToAnother_thenTheirAddressesAreEqual() {
|
||||
String constantString = "interned Baeldung";
|
||||
String newString = new String("interned Baeldung");
|
||||
|
||||
assertThat(constantString).isNotSameAs(newString);
|
||||
|
||||
String internedString = newString.intern();
|
||||
|
||||
assertThat(constantString).isSameAs(internedString);
|
||||
}
|
||||
}
|
||||
13
java-strings-ops/src/test/resources/.gitignore
vendored
Normal file
13
java-strings-ops/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user