When I try to run my program I get this:
System.ArgumentOutOfRangeException: "Index and length must refer to a location within the string. Arg_ParamName_Name"
static List<string> strToList(string s)
{
// input = 00:00:00AM
// 0123456789
List<string> a = new List<string> { };
a.Add(s.Substring(0, 2)); //hh [0]
a.Add(s.Substring(3, 5)); //mm [1]
a.Add(s.Substring(6, 8)); //ss [2]
a.Add(s.Substring(8, 10)); //am [3]
return a;
}
string s = "12:01:00PM";
List<string> a = strToList(s);
foreach (var x in a) {
Console.WriteLine(x);
}
CodePudding user response:
Substing([index],[length])
static List<string> strToList(string s)
{
// input = 00:00:00AM
// 0123456789
List<string> a = new List<string> { };
a.Add(s.Substring(0, 2)); //hh [0]
a.Add(s.Substring(3, 2)); //mm [1]
a.Add(s.Substring(6, 2)); //ss [2]
a.Add(s.Substring(8, 2)); //am [3]
return a;
}
CodePudding user response:
The second argument is the length of the string you want to retrieve.
So s.Substring(0,3)
takes the first three characters. (starting at index 0)
s.Substring(2,5)
takes 5 characters starting at index 2.