Kerberos
Kerberos

Reputation: 105

C# substring out of range

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?

Upvotes: 8

Views: 15697

Answers (3)

Xerillio
Xerillio

Reputation: 5259

Replace line 3 of OP code with this:

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

Upvotes: 4

Enigmativity
Enigmativity

Reputation: 117134

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

Upvotes: 9

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174720

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

Upvotes: 3

Related Questions