Substring, if the string is not long enough replace chars with spaces

c#, substring

Solution

Use String.PadRight

myString.PadRight(3, ' ');
// do SubString here..

You could also create a `.Left` extension method that doesn't throw an exception when the string isn't big enough:

public static string Left(this string s, int len)
{
    if (len == 0 || s.Length == 0)
        return "";
    else if (s.Length <= len)
        return s;
    else
        return s.Substring(0, len);
}

Usage:

myString.Left(3);

Problem

I'm trying to compare first 3 chars of a string, i'm trying to use substring then compare. The strings are read from an input file, and the string may not be 3 chars long. if an string is not 3 chars long i want the substring method to replace the empty chars with spaces. How would i go about doing that. Current code throws an exeption when the string is not long enough.

Original source