James
James

Reputation: 386

Why does TrimStart trims a char more when asked to trim "PRN.NUL"?

Here is the code:

namespace TrimTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string ToTrim = "PRN.NUL";
            Console.WriteLine(ToTrim);
            string Trimmed = ToTrim.TrimStart("PRN.".ToCharArray());
            Console.WriteLine(Trimmed);
            ToTrim = "PRN.AUX";
            Console.WriteLine(ToTrim);
            Trimmed = ToTrim.TrimStart("PRN.".ToCharArray());
            Console.WriteLine(Trimmed);
            ToTrim = "AUX.NUL";
            Console.WriteLine(ToTrim);
            Trimmed = ToTrim.TrimStart("AUX.".ToCharArray());
            Console.WriteLine(Trimmed);
        }
    }
}

The output is like this:

PRN.NUL

UL

PRN.AUX

AUX

AUX.NUL

NUL

As you can see, the TrimStart took out the N from NUL. But it doesn't do that for other strings even if it started with PRN.

I tried with .NET Framework 3.5 and 4.0 and the results are same. Are there any explanation on what causes this behavior?

Upvotes: 2

Views: 1119

Answers (3)

Jacob
Jacob

Reputation: 3698

@MattiVirkkunen's answer is correct. However, here is a solution, use this extension method instead of RemoveStart method to get your desired results.

public static String RemoveStart(this string s, string text)
{
    return s.Substring(s.IndexOf(s) + text.Length, s.Length - text.Length);
}

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

String.TrimStart works on a character level. What you're doing is you're telling it to remove any "P", "R", "N" or "." characters from the start - therefore the first N after the dot also gets removed.

If you want to remove a certain string from the start of the string, first use StartsWith to ensure it's there and then Substring to take the correct part of the string.

Upvotes: 10

user1228
user1228

Reputation:

Try this:

string ToTrim = "PRN.NUL";
string Trimmed = ToTrim.TrimStart(".NRP".ToCharArray());
Console.WriteLine(Trimmed);

Notice anything?

Upvotes: 2

Related Questions