C# Faster way to truncate a string

Very often I found this problem and now I got a solution!

I’ve compared some methods and I was decided which one. But I verified time (if you want to know how, read this post) of them and the final solutions are:

static string TruncateLongString(string str, int maxLength)
{
    return str.Substring(0, Math.Min(str.Length, maxLength));
}

or

string TruncateString(string str, int maxLength)
{
    return new string(str.Take(maxLength).ToArray());
}

The best solution than even is the second one!

TruncateString

Leave a comment

Send a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.