Abbreviates a String using ellipses in Java using Apache Commons Lang
Tags: Apache Commons Apache Commons Lang StringUtils String
Introduction
In this post we show how to use Apache Commons Lang library to abbreviate a String using ellipses. We provide multiple Java code examples on how to use StringUtils.abbreviate() utility method to achieve our goal.
Setup Apache Commons Lang in Java project
If you are using Gradle build then add the following dependency configuration into build.gradle file.
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.11'
Or add the following dependency XML tag to pom.xml file if you are using Maven build.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
Or download commons-lang3-3.11.jar file from Apache Commons Lang download page at commons.apache.org
StringUtils.abbreviate() with input String and max length value
Following Java code example to convert your input String with shorter String and append “…” at the end.
import org.apache.commons.lang3.StringUtils;
public class StringUtilsAbbreviateExample1 {
public static void main(String[] args) {
String testString = "This is a test Java application to show how to use string utilities.";
String result = StringUtils.abbreviate(testString, 35);
System.out.println(result);
}
}
This is a test Java application ...
StringUtils.abbreviate() with input String, offset and max length value
import org.apache.commons.lang3.StringUtils;
public class StringUtilsAbbreviateExample2 {
public static void main(String[] args) {
String testString = "This is a test Java application to show how to use string utilities.";
String result = StringUtils.abbreviate(testString, 10, 30);
System.out.println(result);
}
}
...test Java application to...
StringUtils.abbreviate() with provided marker
With following Java code example you can custom the marker to append “***” to your output String.
import org.apache.commons.lang3.StringUtils;
public class StringUtilsAbbreviateExample3 {
public static void main(String[] args) {
String testString = "This is a test Java application to show how to use string utilities.";
String result = StringUtils.abbreviate(testString, "***", 35);
System.out.println(result);
}
}
This is a test Java application ***
StringUtils.abbreviate() with provided marker and offset
import org.apache.commons.lang3.StringUtils;
public class StringUtilsAbbreviateExample4 {
public static void main(String[] args) {
String testString = "This is a test Java application to show how to use string utilities.";
String result = StringUtils.abbreviate(testString, "***", 10, 30);
System.out.println(result);
}
}
***test Java application to***
Happy Coding 😊