How do I truncate a .NET string?

2019-01-04 06:15发布

I would like to truncate a string such that its length is not longer than a given value. I am writing to a database table and want to ensure that the values I write meet the constraint of the column's datatype.

For instance, it would be nice if I could write the following:

string NormalizeLength(string value, int maxLength)
{
    return value.Substring(0, maxLength);
}

Unfortunately, this raises an exception because maxLength generally exceeds the boundaries of the string value. Of course, I could write a function like the following, but I was hoping that something like this already exists.

string NormalizeLength(string value, int maxLength)
{
    return value.Length <= maxLength ? value : value.Substring(0, maxLength);
} 

Where is the elusive API that performs this task? Is there one?

28条回答
对你真心纯属浪费
2楼-- · 2019-01-04 06:21

There isn't a Truncate() method on string, unfortunately. You have to write this kind of logic yourself. What you can do, however, is wrap this in an extension method so you don't have to duplicate it everywhere:

public static class StringExt
{
    public static string Truncate(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Length <= maxLength ? value : value.Substring(0, maxLength); 
    }
}

Now we can write:

var someString = "...";
someString = someString.Truncate(2);
查看更多
三岁会撩人
3楼-- · 2019-01-04 06:21

The .NET Framework has an API to truncate a string like this:

Microsoft.VisualBasic.Strings.Left(string, int);

But in a C# app you'll probably prefer to roll your own than taking a dependency on Microsoft.VisualBasic.dll, whose main raison d'etre is backwards compatibility.

查看更多
Fickle 薄情
4楼-- · 2019-01-04 06:21

I know this is an old question, but here is a nice solution:

public static string Truncate(this string text, int maxLength, string suffix = "...")
{
    string str = text;
    if (maxLength > 0)
    {
        int length = maxLength - suffix.Length;
        if (length <= 0)
        {
            return str;
        }
        if ((text != null) && (text.Length > maxLength))
        {
            return (text.Substring(0, length).TrimEnd(new char[0]) + suffix);
        }
    }
    return str;
}

var myString = "hello world"
var myTruncatedString = myString.Truncate(4);

Returns: hello...

查看更多
\"骚年 ilove
5楼-- · 2019-01-04 06:21

This is the code I usually use:

string getSubString(string value, int index, int length)
        {
            if (string.IsNullOrEmpty(value) || value.Length <= length)
            {
                return value;
            }
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = index; i < length; i++)
            {
                sb.AppendLine(value[i].ToString());
            }
            return sb.ToString();
        }
查看更多
再贱就再见
6楼-- · 2019-01-04 06:23

TruncateString

public static string _TruncateString(string input, int charaterlimit)
{
    int characterLimit = charaterlimit;
    string output = input;

    // Check if the string is longer than the allowed amount
    // otherwise do nothing
    if (output.Length > characterLimit && characterLimit > 0)
    {
        // cut the string down to the maximum number of characters
        output = output.Substring(0, characterLimit);
        // Check if the character right after the truncate point was a space
        // if not, we are in the middle of a word and need to remove the rest of it
        if (input.Substring(output.Length, 1) != " ")
        {
            int LastSpace = output.LastIndexOf(" ");

            // if we found a space then, cut back to that space
            if (LastSpace != -1)
            {
                output = output.Substring(0, LastSpace);
            }
        }
        // Finally, add the "..."
        output += "...";
    }
    return output;
}
查看更多
来,给爷笑一个
7楼-- · 2019-01-04 06:24

I'd Recommend using the substring method for the same effective functionality.

    // Gets first n characters.
    string subString = inputString.Substring(0, n);

This has the benefit of letting you splice your string from either side or even somewhere in the middle without writing additional methods. Hope that helps :)

For additional reference: https://www.dotnetperls.com/substring

查看更多
登录 后发表回答