Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

substring

c#

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.

like image 703
zaza Avatar asked Dec 02 '22 23:12

zaza


1 Answers

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);
like image 107
mellamokb Avatar answered Dec 24 '22 01:12

mellamokb