I want to move all pair of letters in this way but i have an error: System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string. Arg_ParamName_Name' I dont understand what problem is.
using System;
using System.Collections.Generic;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string str = "helloworld";
string[] str2 = new string[5];
str2[0] = str.Substring(0, 2);
str2[1] = str.Substring(2, 4);
str2[2] = str.Substring(4, 6);
str2[3] = str.Substring(6, 8);
str2[4] = str.Substring(8, 10);
Console.WriteLine(str2);
}
}
}
CodePudding user response:
by https://docs.microsoft.com/en-us/dotnet/api/system.string.substring?view=net-6.0
public string Substring (int startIndex, int length);
note startIndex=6 length=8 is out side of str(str.Length = 10)
CodePudding user response:
The Substring method of C#, takes the parameters as starting index of the substring in string, i.e. the position of your substring in the string and the length of this substring, i.e. how many characters should be there in the substring (including the starting index's character).
Thus at line str[3] = str.Substring(6, 8)
it tries to go to index 6 and then tries to add 8 characters from there... which it can't since there are only 4 (i.e. the indexes 6, 7, 8, 9).
Thus it raises the exception.
Hope this helps :-)