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

前端 未结 8 1189
故里飘歌
故里飘歌 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题