HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Truncate String Method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
truncatestringmethod

Problem

I have 2 Truncate string methods.

First:

public static string Truncate(string source, int length)
    {
    if (source.Length > length)
    {
        source = source.Substring(0, length);
    }
    return source;
    }


Second:

public static string Truncate2(string source, int length)
    {
    return source.PadRight(length).Substring(0, length).Trim();
    }


Which of these methods is better, faster?

Solution

The question is moot, as the methods give different results. It doesn't matter if a method is faster, better, simpler, nicer, fancier or cooler if it doesn't work properly.

The first method works as expected. It always truncates the string to the desired length, if the string is long enough to truncate. (Note though that this could break a combination of unicode characters used to compose a character, but that's a whole different level of expectations.)

The second method will behave badly if the string that you try to truncate contains whitespace characters in the "wrong" place.

For example, Truncate2("A B", 3) returns "A" instead of "A ".

The method will even crash in some situations where it should just return the input unchanged. To get an OutOfMemoryException you can call Truncate2("", Int32.MaxValue).

Context

StackExchange Code Review Q#71148, answer score: 12

Revisions (0)

No revisions yet.