1

生成されるタイトルテキストがたくさんありますが、それらはすべて異なります.Lengthが、文字列の特定の開始インデックスで、最も近いスペースを見つけて、その後のテキストとスペースを削除し、「...」を追加します。

最も重要な部分は、49 の長さを延長しないことです。

例:

"What can UK learn from Spanish high speed rail when its crap"

私はそれが次のようになることを確認したい:

"What can UK learn from Spanish high speed rail..."

ここまで作成した

if (item.title.Length >= 49)
{
    var trim = item.title.Substring(' ', 49) + "...";
}

しかし、これは次のことができます:

"What can UK learn from Spanish high speed rail it..."

これは間違っています。

あらゆる種類のヘルプや、これを達成する方法に関するあらゆる種類のヒントを歓迎します。

4

2 に答える 2

2

これは最後のスペースでトリミングする必要があり、許可された部分にスペースがない場合も処理します。

public static string TrimLength(string text, int maxLength)
{
    if (text.Length > maxLength)
    {
        maxLength -= "...".Length;
        maxLength = text.Length < maxLength ? text.Length : maxLength;
        bool isLastSpace = text[maxLength] == ' ';
        string part = text.Substring(0, maxLength);
        if (isLastSpace)
            return part + "...";
        int lastSpaceIndexBeforeMax = part.LastIndexOf(' ');
        if (lastSpaceIndexBeforeMax == -1)
            return part + "...";
        else
            return text.Substring(0, lastSpaceIndexBeforeMax) + "...";
    }
    else
        return text;
}

デモ

イギリスはスペインの高速鉄道から何を学ぶことができるか...

于 2013-05-08T21:32:24.417 に答える
0

どうぞ。この方法は、非常に長い単語を使用している場合は失敗する可能性がありますが、この方法で作業を開始できます。

public static string Ellipsify(string source, int preferredWidth)
{
    string[] words = source.Split(' '); //split the sentence into words, separated by spaces
    int readLength = 0;
    int stopAtIndex = 0;
    for(int i = 0; i < words.Length; i++) {
        readLength += words[i].Length; //add the current word's length
        if(readLength >= preferredWidth) { //we've seen enough characters that go over the preferredWidth
            stopAtIndex = i;
            break;
        }
        readLength++; //count the space
    }
    string output = "";
    for(int i = 0; i < stopAtIndex; i++)
    {
        output += words[i] + " ";
    }
    return output.TrimEnd() + "..."; //add the ellipses
}
于 2013-05-08T21:38:50.437 に答える