开发者

Truncate string and add word after the nth word

I have a string which has values like "Zesty Bean Bites South of the Border".

I would like to cut it down to three words and append a开发者_如何学运维n ellipsis, yielding "Zesty Bean Bites..."

I tried using the substring() method but it won't split on words.


This handles if there are fewer than three strings.

I'd also consider doing it by character counts:

public string NewTitle(string OldTitle)
    {
        int HowManyWords = 3;
        string RetValue = "";
        string[] parts = OldTitle.Split(' ');
        for (int i = 0; i < parts.Length; i++)
        {
            if (i == 0)
            {
                RetValue += parts[i];
            }
            else
            {
                RetValue += " " + parts[i];
            }
            if (i >= (HowManyWords-1))
            {
                break;
            }
        }
        return RetValue;
    }


Use the String.Split method and use the 'space' character as the delimiter. Then use the String.Join method to join them together.


This should do it:

string title = "Zesty Bean Bites South of the Border";
string[] aParts = title.split(' ');
string newTitle = aParts[0] + aParts[1] + aParts[2] + "...";

If you need the rest of the string after the ellipsis, continue with:

newTitle += aParts[3] + aParts[4] + aParts[5] + aParts[6];

Of course, if the title length varies, this would be more appropriate in a loop, and adding the ellipsis after aParts[2]. To be safe, check aParts.Length to make sure that you actually HAVE three words to put the ellipsis after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜