tl;博士
截断时,您似乎要求在最后一个位置添加 ellipsis (…) 字符。这是操作输入字符串的单行代码。
String input = "abcdefghijkl";
String output = ( input.length () > 10 ) ? input.substring ( 0 , 10 - 1 ).concat ( "…" ) : input;
看到这个code run live at IdeOne.com.
abcdefghi…
三元运算符
我们可以使用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.
;
看到这个code run live at IdeOne.com.
abcdefghi…
Java 流
Java Streams 工具使这变得有趣,从 Java 9 及更高版本开始。有趣,但可能不是最好的方法。
我们使用code points 而不是char 值。 char 类型是旧的,并且仅限于 a subset of 所有可能的 Unicode 字符。
String input = "abcdefghijkl" ;
int limit = 10 ;
String output =
input
.codePoints()
.limit( limit )
.collect( // Collect the results of processing each code point.
StringBuilder::new, // Supplier<R> supplier
StringBuilder::appendCodePoint, // ObjIntConsumer<R> accumulator
StringBuilder::append // BiConsumer<R,R> combiner
)
.toString()
;
如果我们截断了多余的字符,请将最后一个字符替换为 ellipsis。
if ( input.length () > limit )
{
output = output.substring ( 0 , output.length () - 1 ) + "…";
}
如果我能想出一种方法将流线与“如果超出限制,则省略”部分放在一起。