abbreviateMiddle
is a static method of the StringUtils
class that is used to abbreviate a string to the passed length by replacing the middle characters with the supplied replacement string.
Abbreviation is a shortened form of a word or phrase.
The method works only if the following conditions are met:
null
.StringUtils
StringUtils
is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the StringUtils
class as follows:
import org.apache.commons.lang3.StringUtils;
public static String abbreviateMiddle(final String str, final String middle, final int length)
The function takes on the following parameters, as described below:
final String str
is the string to abbreviate.final String middle
is the string to use as the replacement string.final int length
is the length of the abbreviated string.This method returns the abbreviated string.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {String s = "educative";int length = 5;String middleString = "...";System.out.printf("Abbreviation Middle of %s is %s", s, StringUtils.abbreviateMiddle(s, middleString, length));System.out.println();s = "educative";length = 8;middleString = "#";System.out.printf("Abbreviation Middle of %s is %s", s, StringUtils.abbreviateMiddle(s, middleString, length));System.out.println();s = "educative";length = 10;middleString = "#";System.out.printf("Abbreviation Middle of %s is %s", s, StringUtils.abbreviateMiddle(s, middleString, length));System.out.println();}}
"educative"
"..."
5
The method will replace the middle characters with the middle string and return e...e
.
"educative"
"#"
8
The method will replace the middle characters with the middle string and return educ#ive
, with a length that is equal to the length passed.
"educative"
"#"
10
This method will return the input string because the length passed is greater than the length of the input string.
The output of the code will be as follows:
Abbreviation Middle of educative is e...e
Abbreviation Middle of educative is educ#ive
Abbreviation Middle of educative is educative