84

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 code to do this already, but I need to limit Strings, doubles and ints to a fixed-width size that is hard-coded in the code.

So, suppose I want to print a fixed-width table with

    int,string,double,string
    int,string,double,string
    int,string,double,string
    int,string,double,string

    and the fixed widths are: 4, 5, 6, 6.

If a value exceeds this width, the last characters need to be cut off. So for example:

    124891, difference, 22.348, montreal

the strings that need to be printed ought to be:

    1248 diffe 22.348 montre

I am thinking I need to do something in the constructor that forces a string not to exceed a certain number of characters. I will probably cast the doubles and ints to a string, so I can enforce the maximum width requirements.

I don't know which method does this or if a string can be instantiated to behave taht way. Using the formatter only helps with the fixed-with formatting for printing the string, but it does not actually chop characters that exceed the maximum length.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Flethuseo
  • 5,969
  • 11
  • 47
  • 71

8 Answers8

192

You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So

System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");

will produce

'abc' '  a'

(you can remove quotes, obviously).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Jaksa
  • 2,007
  • 2
  • 12
  • 7
103

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.

Claes Mogren
  • 2,126
  • 1
  • 26
  • 34
GETah
  • 20,922
  • 7
  • 61
  • 103
36

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);
mrdavidkendall
  • 469
  • 4
  • 3
28

You can use the Apache Commons StringUtils.substring(String str, int start, int end) static method, which is also null safe.

See: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#substring%28java.lang.String,%20int,%20int%29

and http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.1961

radistao
  • 14,889
  • 11
  • 66
  • 92
khriskooper
  • 767
  • 8
  • 18
  • 12
    Even easier: use the [left method](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#left-java.lang.String-int-). – beat Feb 02 '17 at 10:26
  • 4
    Very excessive to add a library to truncate a string. Caution for this solution would be to only use this if you already are using commons – Patrick Michaelsen Apr 03 '18 at 17:28
25

You can achieve this easily using

    shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
Arade
  • 567
  • 6
  • 14
14

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

Gibolt
  • 42,564
  • 15
  • 187
  • 127
3

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

Moesio
  • 3,100
  • 1
  • 27
  • 36
2

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.

Ashwinee K Jha
  • 9,187
  • 2
  • 25
  • 19
  • Well, maybe I am using it wrong. but it does not actually change the length of my string. I have used the formatter with no effect. It does print stuff nicely, but it doesn't change string's lengths: Formatter fmt = new Formatter(); // Corresponding formats for declared members String hardCodedFormat = "%5s%5s"; // %20s String m_Project; String name = "mynameis"; String name2 = "ted123"; fmt.format(hardCodedFormat, name, name2); System.out.println(fmt); – Flethuseo Dec 03 '11 at 18:30
  • 4
    @Flethuseo You should be able to truncate the strings. Try this: System.err.format("%1$.5s", "A long string"); – Roger Lindsjö Dec 03 '11 at 22:45