I need to create a summary table at the end of a log with some values that are obtained inside a class. The table needs to be printed in fixed-width format. I have the cod
For readability, I prefer this:
if (inputString.length() > maxLength) {
inputString = inputString.substring(0, maxLength);
}
over the accepted answer.
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
You can achieve this easily using
shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
Ideally you should try not to modify the internal data representation for the purpose of creating the table. Whats the problem with String.format()? It will return you new string with required width.
Use this to cut off the non needed characters:
String.substring(0, maxLength);
Example:
String aString ="123456789";
String cutString = aString.substring(0, 4);
// Output is: "1234"
To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
If you want your integers and doubles to have a certain length then I suggest you use NumberFormat to format your numbers instead of cutting off their string representation.
If you just want a maximum length, use StringUtils.left
! No if
or ternary ?:
needed.
int maxLength = 5;
StringUtils.left(string, maxLength);
Output:
null -> null
"" -> ""
"a" -> "a"
"abcd1234" -> "abcd1"
Left Documentation
The solution may be java.lang.String.format("%" + maxlength + "s", string).trim()
, like this:
int maxlength = 20;
String longString = "Any string you want which length is greather than 'maxlength'";
String shortString = "Anything short";
String resultForLong = java.lang.String.format("%" + maxlength + "s", longString).trim();
String resultForShort = java.lang.String.format("%" + maxlength + "s", shortString).trim();
System.out.println(resultForLong);
System.out.println(resultForShort);
ouput:
Any string you want w
Anything short