2

I am reading a text file using C#.Net v3.5 express 2010 containing integers in the format

18 11 2 18 3 14 1 0 1 3 22 15 0 6 8 23 18 1 3 4 10 15 24 17 17 16 18 10 17 18 23 17 11 19 

by

string[] code = System.IO.File.ReadAllLines(@"C:\randoms\randnum.txt");

i then placethis into a string by

string s1 = Convert.ToString(code);

And need to be able to read this into an int array for some mathematical processing.

I've tried everything suggested on this site under other posts on this topic, including parsing, and covert array but once I attempt this I get the dreaded "input string is not in a correct format" message

2
  • why are you converting string[] to string again?? Commented Nov 3, 2014 at 23:53
  • you will have to convert each single value to integer Commented Nov 3, 2014 at 23:53

5 Answers 5

2

you can use LINQ:

var ints = code.SelectMany(s => s.Split(' ')).Select(int.Parse).ToList();

This will take your list of space-separated numbers and flatten them into a one-dimensional List of ints

Sign up to request clarification or add additional context in comments.

1 Comment

Tried this first with the same result unfortunately.
2
var intArray =  File.ReadAllText(@"C:\randoms\randnum.txt")
        .Split((char[]) null, StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse).ToArray();

2 Comments

I didn't realize Split() worked that way with null. I like this solution since it assumes any amount of whitespace between each integer.
Works superbly. Thank you
2

Some of these answers are great, but if your file contains any strings that can't be converted to an int, int.Parse() will throw an exception.

Although slightly more expensive, consider doing a TryParse instead. This gives you some Exception handling:

int tmp = 0; // Used to hold the int if TryParse succeeds

int[] intsFromFile = System.IO.File
        .ReadAllText(@"C:\randoms\randnum.txt")
        .Split(null)
        .Where(i => int.TryParse(i, out tmp))
        .Select(i => tmp)
        .ToArray();

6 Comments

OP says that "I am reading a text file using C#.Net v3.5 express 2010 containing integers in the format"
what if the file contains any separators character like '\t' or '\n'? then you loose some of the numbers. "files aren't always in the exact format you expect them to be"
I mean if "files aren't always in the exact format you expect them to be" you should not expect the numbers to be separated just by space character
You can split on null to handle all whitespace.
Yes, but in this application I am writing text files and I've chosen to keep the white space between letters, so delimiters isn't an issue. But you make a valid point
|
0

It's a one-liner, really. This will give you a 1-dimensional array of integers in the file:

private static rxInteger rxInteger = new Regex(@"-?\d+") ;

...

int[] myIntegers1 = rxInteger
                    .Matches( File.ReadAllText(@"C:\foo\bar\bazbat") )
                    .Cast<Match>()
                    .Select( m => int.Parse(m.Value) )
                    .ToArray()
                    ;

If you want it to be a 2-dimensional ragged array, it's not much more complicated:

int[][] myIntegers2 = File
                      .ReadAllLines( @"C:\foo\bar\bazbat" )
                      .Select( s =>
                        rxInteger
                        .Matches(s)
                        .Cast<Match>()
                        .Select( m => int.Parse(m.Value) )
                        .ToArray()
                      )
                      .ToArray()
                      ;

[implementation of validation and error handling left as an exercise for the reader]

Comments

-1

At first glance, it appears the problem is that you're reading in numbers using ReadAllLines. This will return an array of strings where each string represents one line in your file. In your example it appears that your numbers are all on one line. You could use System.IO.File.ReadAllText to get a single string. Then use .Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries); to get the array of strings your looking for.

string allTheText = System.IO.File.ReadAllText(@"C:\randoms\randnum.txt");
string[] numbers = allTheText.Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.