Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String to list index out of range

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading