Truncate means to cut down something and the method is called truncation. In programming, it often refers to the data types or variables. In programming, we often find situations like handling bigger data or maintaining data integrity which requires moving a part of the string. There are various methods in Java programming that can truncate a string.
This article discusses in detail truncation in Java programming and different methods by which a string can be truncated.
How to Truncate a String in Java?
Truncation in Java refers to cutting down digits from the float/double type or removing some characters of a string. The decimal portion of any number can be removed to form an integer. After the truncation has been completed, the number is rounded off to its closest value. So, this can be called approximating a number too. It is often used when numbers are to be divided and the resulting value should be an integer.
Example
Let us consider a number num=639.6383929 and the truncation is applied to have two digits after the decimal point. The resulting integer is 639.63.
Here is a flowchart that describes how different numbers can be truncated:
This article discusses different methods to truncate a string. Let us discuss each method in detail.
Method 1: Utilising the JDK
A string can be truncated by utilizing the JDK. Java has a number of useful functions that enable truncation of a string. Let us discuss different examples to explore different functions to truncate a string in Java.
Example: 1 using substring()
Java string class has a convenient method called substring. substring() gives back part of the string between the indexes that are specified by the user. Let us look at the following code to see how it works:
public class Main {
public static void main(String[] args) {
String txt = "TRUNCATE THIS STRING!";
int len = 14;
String res = substring(txt, len);
System.out.println(res);
}
static String substring(String txt, int len) {
if (txt.length() <= len) {
return txt;
} else {
return txt.substring(0, len);
}
}
}
In the above code,
- The code defines a Java public class main
- The main method public static void main(String[] args) is defined. This is the initial stage where the program gets executed.
- A string txt is initialized that says “TRUNCATE THIS STRING!“. This string will be truncated according to the length specified.
- An integer variable len will be defined whose value will be set to 14. It will be the maximum length, and the txt string will be truncated.
- A substring static method is defined that returns a string and takes two parameters txt and len which were previously defined. This truncates the input string if it exceeds the limit.
- Inside the substring method, there is a conditional check. If the length of the string txt will be lesser or equal, the string will not be truncated. If the length is greater, the method will go to the else block where the substring method will be called.
- The truncated string will be returned and printed through System.out.println().
Output
The output displays how a string is truncated using Java’s substring() method:
Example 2: Using split()
One more to truncate a string is using the split() function. split() separates the string in different segments. “positive lookbehind” is a regular expression feature that matches a particular number of characters coming at the start of the string. Let us look at the following code to see how it works:
public class Main {
public static void main(String[] args) {
String txt = "A Java program is running!";
int len = 14;
String res = split(txt, len);
System.out.println(res);
}
static String split(String text, int length) {
String[] results = text.split("(?<=\\G.{" + length + "})");
return results[0];
}
}
In the above code:
- A static string function named split takes the string parameter text and int variable length. The method helps to split the input string into segments of specific lengths and extracts the first segment
- The method text.split is used to split the input strings. The expression ‘(?<=\\G.{” + length + “})’ where \\Gposition is at the ending of the last match or the beginning of the initial match, .{” + length + “} matches the character repeated to the number of times length is repeated. (?<=…) is a positive look-behind assertion that makes sure that the delimiter is preceded by a particular pattern.
- The returned string is stored in the results array.
- The functionality is then checked out on string txt that says ‘A Java program is running!’. The specified length is 14 so the string will be truncated up to 14 characters.
- The resultant string will be printed through System.out.println(res).
Output
The output displays how a string can be truncated by using the JDK functionality split():
Example 3: Using the Pattern Class
Pattern class runs a regular expression that matches the beginning of the String up to a particular number of characters. Consider for example, {1, “length+”}. The regex should match at least one and at maximum the length of characters. The code below explains how a string can be truncated using the pattern class:
public class Main {
static String pattern(String text, int length) {
Optional<String> result = Pattern.compile(".{1," + length + "}")
.matcher(text)
.results()
.map(MatchResult::group)
.findFirst();
return result.isPresent() ? result.get() : "";
}
public static void main(String[] args) {
String txt = "I love to code!";
int len = 10;
String res = pattern(txt, len);
System.out.println(res);
}
}
In the above code:
- The necessary classes used in the code are imported through import java.util.regex.* and import java.util.*
- A main class is defined that contains the method to truncate a string
- The pattern function takes two parameters text and length to split the text into segments using a regular expression pattern.
- pattern.compile(“.{1,” + length + “}”) compiles the regex pattern that matches the substrings up to the length. The matches are converted to the MatchResult objects and then mapped to get the matched substrings. The first matched substring will be extracted using findFirst and will be saved in an optional.
- The regular expression method returns the matched substring which comes at the beginning. It will return an empty string provided there is no match.
- The main method contains a text string ‘I love to code!’ which will be given as a text parameter to the pattern function with the length parameter as 10. The resultant string will be truncated and it will be displayed as ‘I love to’.
Output
The following output displays how a string can be truncated using the JDK functionality pattern class:
Example 4: charSequence’s codePoints() Method
charSequence’s codePoints() functions convert a string into code point values. Let us look at the following code that discusses how the stream API can be used to truncate a string:
public class Main {
static String codePoints(String text, int length) {
return text.codePoints()
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
public static void main(String[] args) {
String txt = "Java is my favorite programming language!";
int len = 20;
String res = codePoints(txt, len);
System.out.println(res);
}
}
In the above code,
- The main class contains a static string function codePoints that takes the parameters text and length.
- codePoints is called on text which returns a streamnof unicode points for the characters in the text.
- limit(length) limits the number of code points in the stream to the specified length.
- .collect(…) collects the limited code points to the StringBuilder object. For the purpose of collecting the characters, a StringBuilder object is built.
- appendCodePoint specifies how each code point can be appended to StringBuilder. append integrates the code points together.
- The function toString() is called on StringBuilder which gathers the code point to String.
- The main function contains a sample text that says ‘Java is my favorite programming language!’ that will be truncated up to 15 characters. The resulting string will be stored in res and will be printed using System.out.println(res).
Output:
The following output displays how a string can be truncated using the JDK functionality codePoints():
Method 2: Utilizing the Guava Library
A string can be truncated using the Guava library and using its functionalities. Guava library contains different collections like multisets.
Adding Guava Library to pox.xml file
Integrating the Guava library dependency to the pox.xml file will provide functions like split() that can truncate the string. Here is how the library is integrated:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
Integrating the Guava dependency to the pom.xml file can truncate a string. The following code explains how a string can be truncated using the Guava Library:
import com.google.common.base.Splitter;
public class Main {
public static void main(String[] args) {
String txt = "Split the string already!";
int len = 15;
String res = splitter(txt, len);
System.out.println(res);
}
static String splitter(String text, int length) {
Iterable<String> parts = Splitter.fixedLength(length)
.split(text);
return parts.iterator()
.next();
}
}
In the above code:
- The split() functionality from the Guava library is imported.
- The Splitter method takes two parameters: text and length.
- splitter.fixedLength(length) creates an instance splitter that splits the input text according to the given specified length.
- .split(text) is called on Splitter to split the text into different parts resulting in an Iterable<String> which will contain these parts
- parts.iterator().next() gets the first segment from the split parts
- The splitter function is called on a sample string txt that says ‘Split the string already!’ with the len variable equal to 15 which will be the number of characters contained in the first segment.
- The result ‘Split the strin’ will be printed using System.out.println(res)
Output
The following output displays how a string can be truncated using the split() functionality from the Guava library:
Method 3: Utilizing the Apache Commons Library
The Apache Commons Lang library contains a class named “StringUtils” for the manipulation of the strings. It is used when we integrate the Apache Commons dependency to pom.xml.
Adding Guava Library to pox.xml File
Integrating the Guava library dependency to the pox.xml file will provide functions like split() that can truncate the string. Here is how the library is integrated:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> </dependency>
Let us look at different examples that use the Apache Commons Library to truncate the string.
Example 1: Using StringUtils’s left()
The Apache Commons library function StringUtils’s left() can be used to truncate the string. The code to cut down the string using the left() function is given below:
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
String txt = "Coding in Java is Fun!";
int len = 18;
String res = left(txt, len);
System.out.println(res);
}
static String left(String text, int length) {
return StringUtils.left(text, length);
}
}
In the above code:
- The StringUtils’s left() function is imported from the Apaches Commons Library.
- The left() function has text and length as its parameters. Length will be the number of characters to which the text will be truncated.
- The sample string txt “Coding in Java is Fun!” will be truncated up to a length of 18.
- The resulting truncated string ‘Coding in Java is‘ will be printed using System.out.println(res).
Output
The following output displays how a string can be truncated by using the StringUtils’s left() functionality from the Apache Commons Library:
Example 2: Using StringUtils’s truncate()
The Apache Commons library function StringUtils’s truncate() can be used to truncate the string. The code to cut down the string using the truncate() function is given below:
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) { int len = 20;
String txt = "Exploring different coding languages!";
String res = truncate(txt, len);
System.out.println(res);
}
public static String truncate(String text, int length) {
return StringUtils.truncate(text, length);
}
}
In the above code:
- The StringUtils’s truncate() function is imported from the Apaches Commons Library.
- The trucate() function takes two parameters text and length. Length indicates the characters that are truncated from the string.
- The sample string txt “Exploring different coding languages” will be truncated up to a length of 20.
- The resulting truncated string ‘Exploring different’ will be printed using System.out.println(res).
Output
The following output displays how a string can be truncated by using the StringUtils’s left() functionality from the Apache Commons Library:
Conclusion:
A string is truncated by various methods like JDK methods that include substring(), split(), codePoints() functions or libraries like Apache Commons and Guava. These libraries contain different functionalities like split(), truncate(), and left() that can truncate a string up to a specified length. This article discussed different ways a string can be truncated and illustrated the methods with their relevant examples.