Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# substring out of range

Tags:

substring

c#

The problem I am having is that I need to be able to loop over a string, returning 5 characters after the position of the index, then starting 5 characters after.

However when there are less than 5 characters left an out of range error occurs, I thought it would just print the remaining characters of the string.

string string1 = "ghuitghtruighr";
for (int index = 0; index < string1.Length; index += 5)
{
    string subString = string1.Substring(i, 5);
    Console.WriteLine(subString);
}

How can I get it to print what's left of the string when whats remaining is less than 5?

like image 505
Kerberos Avatar asked Feb 08 '16 23:02

Kerberos


3 Answers

You could use the LINQ .Skip(...) & .Take(...) operators like so:

for (int index = 0; index < string1.Length; index += 5)
{
    string subString = new String(string1.Skip(index).Take(5).ToArray());
    Console.WriteLine(subString);
}

That gives:

ghuit
ghtru
ighr
like image 160
Enigmativity Avatar answered Sep 19 '22 11:09

Enigmativity


Replace line 3 of OP code with this:

string subString = string1.Substring(i, string1.Length - i < 5 ? string1.Length - i : 5);

like image 35
Xerillio Avatar answered Sep 21 '22 11:09

Xerillio


You could Substring() from the index to the end of the string and then check whether the resulting substring contains more than 5 characters:

string string1 = "ghuitghtruighr";
for (int index = 0; index < string1.Length; index += 5)
{
    string subString = string1.Substring(index);
    if(subString.Length > 5)
        subString = subString.Substring(0, 5);
    Console.WriteLine(subString);
}

Don't do the above if you have many distinct strings of great length - strings are immutable so calling Substring() twice on every iteration results in an extra string on the heap every time - rather calculate the difference between Length and index like suggested by Xerillio

like image 34
Mathias R. Jessen Avatar answered Sep 18 '22 11:09

Mathias R. Jessen