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?
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
Replace line 3 of OP code with this:
string subString = string1.Substring(i, string1.Length - i < 5 ? string1.Length - i : 5);
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 - string
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With