Home > database >  Adding numbers from list of custom delimieters
Adding numbers from list of custom delimieters

Time:09-27

I am writing program to add numbers from string which will be seperated from delimeters

  private static readonly char[] Separators = { ',', '\n', '/','@'  };

public int Add(string numbers)
{
    if (numbers.Equals(string.Empty))
    {
        return 0;
    }
    
    return numbers.Split(Separators).Select(int.Parse).Sum();
}

When i pass the following string to Add method //@\n2@3 Then i get below error Input string was not in a correct format.

I expect answer to be 5

CodePudding user response:

By default, string.Split will create empty groups if two delimiters are right next to each other. For example "3,,4".Split(','); will produce an array with three elements ("3", empty string, and "4").

You can change this in one of two ways. The first (and probably simpler) is to have the Split ignore empty entries.

numbers.Split(Separators, StringSplitOptions.RemoveEmptyEntries)

Or you can use Where in Linq

numbers.Split(Separators).Where(x => x.Length > 0)

This will prevent elements with a blank string value reaching int.Parse. Of course, there are still other things you should do to validate your input before attempting to parse, but that's another topic.

  •  Tags:  
  • c#
  • Related