Home > Net >  Trouble Converting string [] to int []
Trouble Converting string [] to int []

Time:02-01

using System;
using System.IO;

namespace Test_Arrays_and_Files
{  
    class Program
    {
        static void Main(string[] args)
        {
            string tFile = @"C:\Programming\GLO\DC\dcw.txt";
            string read = File.ReadAllText(tFile);
            string[] test = read.Split(',');
            int[] ints = Array.ConvertAll(test, int.Parse);
            Console.WriteLine(ints[0]);                  
        }        
    }
}

Input Data:

Text File Contents:(1 value per line,)

35,
35,
40,
40,
40,

getting System.FormatException: Input string was not in correct format please help and sorry for bad post I'm new here

CodePudding user response:

There are two issues in your code,

  1. Your string is ending with , which is creating empty record after the split. This is the reason you are getting the error.
  2. Your delimiter should be $",{Environment.NewLine}" not only ','.

So to convert given string to int array, first Trim() the input string by , and then split by $",{Environment.NewLine}".

Like,

using System.Linq;
...
var result = str.Trim(',') //Remove leading and trailing comma(s), You can use `TrimEnd()` as well
      .Split($",{Environment.NewLine}", StringSplitOptions.RemoveEmptyEntries)   //Split by given delimiter.
      .Select(int.Parse)
      .ToArray();    //Convert string[] to int[]

Try online

CodePudding user response:

You're only getting it because the file has a comma at the end, which means Split ends up churning out an empty string in the very last position. int.Parse will choke on the empty string

Plenty of ways you could solve it, one is to tell Split not to return you empties, by changing the split line of your code to:

string[] test = read.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries);

You could trim the comma off the end, but using the above approach would mean your parsing would survive a blank line in the middle of the file too

Generally when parsing strings it's more robust to use TryParse than Parse. TryParse takes in the number variable to set the result to and returns you a Boolean telling if the parsing succeeded

int[] ints = Array.ConvertAll(test, GetIntOrMinusOne);


//put a method helper
private int GetIntOrMinusOne(string s){
  if(int.TryParse(s, out var t)
    return t;
  return -1;
}

For this we need to get a bit more involved with the ConvertAll call. Instead of nominating a "method that converts a string to an int" like int.Parse, we need to write our own mini method that tries to parse and if it fails return something like -1, hen nominate that as the method to call to do the conversion, not int.Parse

You can shorten that code a bit to

int[] ints = Array.ConvertAll(test, s => int.TryParse(s, out var t) ? t : -1);

But I'm not sure that you'll have come across lambdas yet, judging by the style of the rest of the code

  •  Tags:  
  • Related