Kerberos February 2016

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?

Answers


Mathias R. Jessen February 2016

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


Xerillio February 2016

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


Enigmativity February 2016

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

Post Status

Asked in February 2016
Viewed 2,455 times
Voted 8
Answered 3 times

Search




Leave an answer