Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# take a substring of a string

I am taking a line from a file only if that file doen't have a specific pattern.. and i want to take from that line the last 3 chars... my code is:

        while (!line.Contains(pattern))
        {
             String num = line.Substring((line.Length - 3), (line.Length - 2));
             System.Console.WriteLine(num);
        }

but i get an error..

Index and length must refer to a location within the string. Parameter name: length

why i get that? i am starting the new string 3 chars before the end of the line and i stop 2 chars before.. :\

like image 663
tequilaras Avatar asked Dec 21 '22 06:12

tequilaras


1 Answers

Substring takes an offset and then a number of characters to return:

http://msdn.microsoft.com/en-us/library/aa904308%28v=VS.71%29.aspx

So:

String num = line.Substring((line.Length - 3), 3);

This of course assumes that line.Length > 3. You could check with:

String num = (line.Length < 3) ? line : line.Substring((line.Length - 3), 3);
like image 167
Mike Christensen Avatar answered Jan 05 '23 01:01

Mike Christensen