views:

90

answers:

3

Hello all,

I have a small trouble. I want to show just a part of a string for example:

Instead: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."

Just a: "Lorem ipsum dolor sit amet, consetetur sadipscing..."

Which method can I use to do that?

Thanks for a help and take care, Ragims

+1  A: 

Hi, definitely substring. Trust me, Trim is not enough ;)

Trimack
works greate! thank you!
Ragims
+2  A: 

I use a string extension method to do this. Add a method like this to a static class wherever you keep your helper methods:

    /// <summary>
    /// Trim the front of a string and replace with "..." if it's longer than a certain length.
    /// </summary>
    /// <param name="value">String this extends.</param>
    /// <param name="maxLength">Maximum length.</param>
    /// <returns>Ellipsis shortened string.</returns>
    public static string TrimFrontIfLongerThan(this string value, int maxLength)
    {
        if (value.Length > maxLength)
        {
            return "..." + value.Substring(value.Length - (maxLength - 3));
        }

        return value;
    }

This will trim the front of the string, easy enough to fix if the beginning of your string is more important. Then to use this in your view:

Here is my trimmed string: <%: Model.MyValue.TrimFrontIfLongerThan(20) %>

Hope that helps!

Simon Steele
+1  A: 

What I always do is a "short text" and a long text. To avoid that words get cut off in the middle. I dont know if what your exact requirements are.

If it doesnt matter, use substring

Ivo
right solution, thank you!
Ragims