Home > other >  Why do i get this error, 'Input string was not in a correct format.'
Why do i get this error, 'Input string was not in a correct format.'

Time:02-23

I am trying to get an input of #1-1-1 and I need to take the numbers from this string and put them into a list of type int. I have tried to do this using this code:

List<int>numbers = new List<int>();

numbers = Console.ReadLine().Split('-', '#').ToList().ConvertAll<int>(Convert.ToInt32);

Shouldn't the input get split into an array of the numbers I want, then get turned into a list, then get converted into a int list?

CodePudding user response:

Your problem is not the .split('-','#'). This splits the string into a string[] with four entrys (in this example). The first one is an empty string. This cannot be convertet into a Int32.

As a hotfix:

        var numbers = Console.ReadLine().Split('-', '#').ToList();
        //numbers.RemoveAt(0); <- this is also working
        numbers.Remove(string.Empty);
        var ret = numbers.ConvertAll<int>(Convert.ToInt32);

That will work for your "#1-1-1 " case. But you should check for non integer chars in the list before converting.

CodePudding user response:

string input = " #1-1-1";

var numbers = Console.ReadLine().Replace("#", "").Split('-').Select(int.Parse).ToList();

CodePudding user response:

You can do it this way

List<int> numbers = new List<int>();
string[] separators = new string[] { "-", "#" };
numbers = Console.ReadLine().Split(separators,StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll<int>(Convert.ToInt32);
  •  Tags:  
  • c#
  • Related