1

If I have a text file with the string: 100101101

I can read and store this by using the following code:

string text = System.IO.File.ReadAllText(@"writeText.txt");

How can I convert the string into separate numbers and add each number to an array index, do I need to separate each number with a comma? I was thinking I could iterate through the string and for each character convert to an integer and add to array, would this work?

Here is what i am trying:

        int[] arrSetup = new int[9];
        string text = System.IO.File.ReadAllText(@"writeText.txt");

        foreach (char c in text)
        {
            arrSetup[0] = Int32.Parse(c);

        }
deucalion0
  • 2,422
  • 9
  • 55
  • 99
  • 8
    Well, there are various steps there - splitting by commas, parsing integer, storing in an array... what have you tried, and what went wrong? – Jon Skeet Mar 07 '13 at 17:45
  • possible duplicate of [How to split a number into individual digits?](http://stackoverflow.com/questions/4808612/how-to-split-a-number-into-individual-digits) – rs. Mar 07 '13 at 17:47
  • Are you wanting to store it in same format? Are you looking to reverse then store it? Group similar numbers? – Brian Mar 07 '13 at 17:47
  • I have edited my question to show my latest attempt. Thanks – deucalion0 Mar 07 '13 at 17:52

2 Answers2

2

Your data was like this : 100101101.. So Separate by Commas and then add that to integer array is not needed...

So just try like below, it will help you...

        string text = System.IO.File.ReadAllText(@"writeText.txt");
        int[] arr = new int[text.Length];
        for (int i = 0; i < text.Length; i++)
        {
            arr[i] = Convert.ToInt32(text[i].ToString());
        }

Now the integer array arr[] have the Values separately...

Pandian
  • 8,848
  • 2
  • 23
  • 33
  • Excellent this worked perfectly! I will accept as answer once it allows me! Thank you for this, I was almost there! :) – deucalion0 Mar 07 '13 at 17:54
1

Hope this will help ,try it yourself :

        string text = System.IO.File.ReadAllText(@"writeText.txt");
        char[] arr = text.ToCharArray() ;
        int[] nums = {0};
        for (int a = 0; a < 8; a++)
           nums[a] = System.Convert.ToInt32(arr[a]);
J .A
  • 63
  • 1
  • 4
  • 10