Truncate. In Java we often need to ensure a maximum length of Strings. We truncate strings to a length, making Strings that are too long shorter. No built-in method is available.
With substring, we can compose a helpful method to truncate strings. A logical branch, needed to eliminate exceptions, is helpful. This ensures more cases work correctly.
In the tests, the truncate() method works correctly on sizes that are too long (10). It successfully applies substring() to create a 3-char string.
Input: apple
Truncate(3): app
Example code. This program introduces the truncate() method. It receives two parameters—the String to truncate and the length of the desired String.
Detail The if-statement ensures that the substring() method never receives a length that is too long. This avoids errors.
Detail The method does nothing, returning the original string, when the truncate-length is shorter than the String itself.
public class Program {
public static String truncate(String value, int length) {
// Ensure String length is longer than requested size.
if (value.length() > length) {
return value.substring(0, length);
} else {
return value;
}
}
public static void main(String[] args) {
String test = "apple";
// ... Truncate to 3 characters.
String result1 = truncate(test, 3);
System.out.println(result1);
// ... Truncate to larger sizes: no exception occurs.
String result2 = truncate(test, 10);
System.out.println(result2);
String result3 = truncate(test, 5);
System.out.println(result3);
}
}app
apple
apple
Helpful methods, like truncate, are often key to developing more complex programs. Using an abstraction like truncate() makes a more complicated method easier, and clearer, to write.
For performance, truncate() avoids creating strings when possible. It does nothing when no new String is needed. This may help program performance.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.