String TruncateImplement a truncate method for the String class. Check String length before using substring.
This page was last reviewed on Jul 6, 2021.
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.
Shows a method
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.Shows a method
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 6, 2021 (edit).
© 2007-2024 Sam Allen.