Trim a string based on the string length

后端 未结 12 888
無奈伤痛
無奈伤痛 2020-12-12 14:29

I want to trim a string if the length exceeds 10 characters.

Suppose if the string length is 12 (String s=\"abcdafghijkl\"), then the new trimmed string

12条回答
  •  悲&欢浪女
    2020-12-12 15:16

    tl;dr

    You seem to be asking for an ellipsis () character in the last place, when truncating. Here is a one-liner to manipulate your input string.

    String input = "abcdefghijkl";
    String output = ( input.length () > 10 ) ? input.substring ( 0 , 10 - 1 ).concat ( "…" ) : input;
    

    See this code run live at IdeOne.com.

    abcdefghi…

    Ternary operator

    We can make a one-liner by using the ternary operator.

    String input = "abcdefghijkl" ;
    
    String output = 
        ( input.length() > 10 )          // If too long…
        ?                                
        input     
        .substring( 0 , 10 - 1 )         // Take just the first part, adjusting by 1 to replace that last character with an ellipsis.
        .concat( "…" )                   // Add the ellipsis character.
        :                                // Or, if not too long…
        input                            // Just return original string.
    ;
    

    See this code run live at IdeOne.com.

    abcdefghi…

    Java streams

    The Java Streams facility makes this interesting, as of Java 9 and later. Interesting, but maybe not the best approach.

    We use code points rather than char values. The char type is legacy, and is limited to the a subset of all possible Unicode characters.

    String input = "abcdefghijkl" ;
    int limit = 10 ;
    String output =
            input
                    .codePoints()
                    .limit( limit )
                    .collect(                                    // Collect the results of processing each code point.
                            StringBuilder::new,                  // Supplier supplier
                            StringBuilder::appendCodePoint,      // ObjIntConsumer accumulator
                            StringBuilder::append                // BiConsumer combiner
                    )
                    .toString()
            ;
    

    If we had excess characters truncated, replace the last character with an ellipsis.

    if ( input.length () > limit )
    {
        output = output.substring ( 0 , output.length () - 1 ) + "…";
    }
    

    If only I could think of a way to put together the stream line with the "if over limit, do ellipsis" part.

提交回复
热议问题