簡體   English   中英

根據字符串長度修剪字符串

[英]Trim a string based on the string length

如果長度超過 10 個字符,我想修剪字符串。

假設如果字符串長度為 12 ( String s="abcdafghijkl" ),則新修剪的字符串將包含"abcdefgh.."

我怎樣才能做到這一點?

s = s.substring(0, Math.min(s.length(), 10));

在字符串已經短於10的情況下,像這樣使用Math.min可以避免異常。


筆記:

  1. 以上是真正的修剪。 如果您真的想用三個點替換字符串太長的最后一個字符,請使用 Apache Commons StringUtils.abbreviate 請參閱@H6 的解決方案 如果要使用 Unicode 水平省略號字符,請參閱@Basil 的解決方案

  2. 對於String典型實現, s.substring(0, s.length())將返回s而不是分配新的String

  3. 如果您的字符串包含 BMP 之外的 Unicode 代碼點,這可能會出現錯誤1 例如表情符號。 有關適用於所有 Unicode 代碼點的(更復雜的)解決方案,請參閱@sibnick 的解決方案


1 - 不在平面 0(BMP)上的 Unicode 代碼點在String表示為“代理對”(即兩個char值)。 通過忽略這一點,我們可能會將字符串修剪到少於 10 個代碼點,或者(更糟糕的是)在代理對的中間截斷它。 另一方面, String.length()不是 Unicode 文本長度的良好度量,因此基於該屬性進行修剪可能是錯誤的做法。

來自Apache Commons Lang庫的StringUtils.abbreviate可能是你的朋友:

StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."

Commons Lang3甚至允許將自定義字符串設置為替換標記。 例如,您可以設置單個字符省略號。

StringUtils.abbreviate("abcdefg", "\u2026", 6) = "abcde…"

有一個 Apache Commons StringUtils函數可以做到這一點。

s = StringUtils.left(s, 10)

如果 len 字符不可用,或者 String 為 null,則 String 將無異常地返回。 如果 len 為負,則返回空字符串。

StringUtils.left(null, ) = null
StringUtils.left( , -ve) = ""
StringUtils.left("", *) = ""
StringUtils.left("abc", 0) = ""
StringUtils.left("abc", 2) = "ab"
StringUtils.left("abc", 4) = "abc"

StringUtils.Left JavaDocs

禮貌:史蒂夫·麥考利

像往常一樣,沒有人關心 UTF-16 代理對。 查看它們: 實際使用中最常見的非 BMP Unicode 字符有哪些? 甚至 org.apache.commons/commons-lang3 的作者

您可以在此示例中看到正確代碼和普通代碼之間的區別:

public static void main(String[] args) {
    //string with FACE WITH TEARS OF JOY symbol
    String s = "abcdafghi\uD83D\uDE02cdefg";
    int maxWidth = 10;
    System.out.println(s);
    //do not care about UTF-16 surrogate pairs
    System.out.println(s.substring(0, Math.min(s.length(), maxWidth)));
    //correctly process UTF-16 surrogate pairs
    if(s.length()>maxWidth){
        int correctedMaxWidth = (Character.isLowSurrogate(s.charAt(maxWidth)))&&maxWidth>0 ? maxWidth-1 : maxWidth;
        System.out.println(s.substring(0, Math.min(s.length(), correctedMaxWidth)));
    }
}

s = s.length() > 10 ? s.substring(0, 9) : s;

或者,如果您手頭沒有 StringUtils,您可以使用此方法:

public static String abbreviateString(String input, int maxLength) {
    if (input.length() <= maxLength) 
        return input;
    else 
        return input.substring(0, maxLength-2) + "..";
}

以防萬一您正在尋找一種方法來修剪和保留字符串的最后 10 個字符。

s = s.substring(Math.max(s.length(),10) - 10);

這個問題是在 Java 上提出的,但它是在 2014 年。
如果你現在使用 Kotlin,它很簡單:

yourString.take(10)

返回包含此字符串中前 n 個字符的字符串,如果此字符串較短,則返回整個字符串。

文檔

tl;博士

截斷時,您似乎在最后一個地方要求使用省略號( ) 字符。 這是一個用於操作輸入字符串的單行代碼。

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

查看此代碼在 IdeOne.com 上實時運行。

abcdefghi…

三元運算符

我們可以使用三元運算符來制作單線

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.
;

查看此代碼在 IdeOne.com 上實時運行。

abcdefghi…

Java 流

從 Java 9 及更高版本開始,Java Streams 工具使這變得有趣。 有趣,但也許不是最好的方法。

我們使用代碼點而不是char值。 char類型是遺留的,僅限於所有可能的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()
        ;

如果我們截斷了多余的字符,請用省略號替換最后一個字符。

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

如果我能想出一種方法將流線與“如果超過限制,做省略號”部分放在一起。

str==null ? str : str.substring(0, Math.min(str.length(), 10))

要么,

str==null ? "" : str.substring(0, Math.min(str.length(), 10))

適用於空值。

// 這就是使用 .. 縮短字符串長度的方法 // 將以下方法添加到您的類中

private String abbreviate(String s){
  if(s.length() <= 10) return s;
  return s.substring(0, 8) + ".." ;
}

這是 Kotlin 解決方案

一條線,

if (yourString?.length!! >= 10) yourString?.take(90).plus("...") else yourString

傳統的,

if (yourString?.length!! >= 10) {
  yourString?.take(10).plus("...")
 } else {
  yourString
 }

如果長度超過10個字符,我想修剪字符串。

假設字符串長度為12( String s="abcdafghijkl" ),則新的修剪后的字符串將包含"abcdefgh.."

我該如何實現?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM