Limiting the number of characters in a string, and chopping off the rest

前端 未结 8 1160
故里飘歌
故里飘歌 2020-12-08 02:02

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

相关标签:
8条回答
  • 2020-12-08 02:09

    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);
    
    0 讨论(0)
  • 2020-12-08 02:12

    You can achieve this easily using

        shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
    
    0 讨论(0)
  • 2020-12-08 02:19

    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.

    0 讨论(0)
  • 2020-12-08 02:21

    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.

    0 讨论(0)
  • 2020-12-08 02:28

    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

    0 讨论(0)
  • 2020-12-08 02:28

    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

    0 讨论(0)
提交回复
热议问题