[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1101
  • Last Modified:

Convert string to Integer

Hi Experts,

I am using a function that can save a text file lines to an array. But the array is string and I want to save them to integer array?
Is there a way to convert the string array to integer that I can used it with the function attached?

The code attached from:http://www.dotnetperls.com/readline

Note: I am using c# 2008
Thanks
Regards
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        const string f = "TextFile1.txt";

        // 1
        // Declare new List.
        List<string> lines = new List<string>();

        // 2
        // Use using StreamReader for disposing.
        using (StreamReader r = new StreamReader(f))
        {
            // 3
            // Use while != null pattern for loop
            string line;
            while ((line = r.ReadLine()) != null)
            {
                // 4
                // Insert logic here.
                // ...
                // "line" is a line in the file. Add it to our List.
                lines.Add(line);
            }
        }

        // 5
        // Print out all the lines.
        foreach (string s in lines)
        {
            Console.WriteLine(s);
        }
    }
}

Open in new window

0
Sat80
Asked:
Sat80
  • 11
  • 9
  • 7
  • +3
5 Solutions
 
käµfm³d 👽Commented:
So is the value of "line" some integer, but in string form? If so, you could do this:
List<string> lines = new List<string>();

...

try
{
    lines.Add(Convert.ToInt32(line));
}
catch  // You'll want to catch a specific exception.
       //  I think the proper exception is InvalidFormatException
{
    // Found invalid number
}

Open in new window

0
 
Fernando SotoRetiredCommented:
What does the input file look like? Can you post a sample.
0
 
50calCommented:
To convert from a string to an integer you can user
int myInt = Convert.toint32(StringValue);

The syntax may be a tad off there.

50cal.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Sat80Author Commented:
Hi, an example of the data on the text file is:
1,2,3,4,5,6
7,8,9,10,11,12
5,4,6,8
1,2

@kaufmed, can you please check the function? as you can see the  lines is string and it should be int? when I changes to int then it did not work! thanks.
0
 
Fernando SotoRetiredCommented:
Hi Sat80;

This should do what you want.

const string f = "TextFile1.txt";

// 1
// Declare new List.
List<int> lines = new List<int>();

// 2
// Use using StreamReader for disposing.
using (StreamReader r = new StreamReader(f))
{
    // 3
    // Use while != null pattern for loop
    string line;
    while ((line = r.ReadLine()) != null)
    {
        // 4
        // Insert logic here.
        line.Split(new char[] {','} , StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(i => { lines.Add(Convert.ToInt32(i)); });
    }
}

// If you need the integers in an array and not a Lint<int>
int[] myInts = lines.ToArray();

// 5
// Print out all the lines.
// Iterate through List<int> change collection in foreach to lines
// Iterate through array of int's leave collection in foreach as myInts
foreach (int s in myInts)
{
    Console.WriteLine(s.ToString());
}

Open in new window


Fernando
0
 
TinTombStoneCommented:
Uses a List<Int> rather than a string
then parses each line into numbers
of course we have to convert back to string to display!

using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
       static void Main()
       {
       const string f = "c:\\Sample\\Sample.txt";

        // 1
        // Declare new List.
        List<int> lines = new List<int>();

        // 2
        // Use using StreamReader for disposing.
        using (StreamReader r = new StreamReader(f))
        {
            // 3
            // Use while != null pattern for loop
            string line;
            while ((line = r.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                foreach (string word in words)
                {                
                     lines.Add(Convert.ToInt32(word));
                }
            }
        }

        // 5
        // Print out all the lines.
        foreach (Int32 n in lines)
        {
            Console.WriteLine(n.ToString());
        }
    }

    }
}
0
 
Sat80Author Commented:
Hi Fernadom,
Thanks for the help, I got one error:
Error	1	'System.Array' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

Open in new window

Can you please help me to solve it?
0
 
Sat80Author Commented:
@TinTombStone, thanks! But as you can see, when we have a text file like this:
1,2,3,4,5,6
7,8,9,10,11,12
5,4,6,8
1,2

Then the int array items (lines) will include the file lines as:
1
2
3
4
5
6
7
8
9
.
.
.

And it should to save the whole line as one row, so the array should be like this:
1,2,3,4,5,6
7,8,9,10,11,12
5,4,6,8
1,2

So, it will be the same as the txt file lines, thanks.
0
 
käµfm³d 👽Commented:
You didn't mention previously that each line had a comma-separated list of integers. Please have a look at FernandoSoto's offering ( http:#34945739 ).
0
 
Fernando SotoRetiredCommented:
Make sure you have the using statement

using System.Linq;
0
 
starlite551Commented:
Try this code :
public List<int> GetIntegralValues(string txtFilePath)
        {
            List<int> intList = new List<int>();
            string content = "";
            using (FileStream fs = new FileStream(txtFilePath,FileMode.Open,FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    content = sr.ReadToEnd();

                    foreach (string line in content.Split(new string[]{"\n","\r"},StringSplitOptions.RemoveEmptyEntries))
                    {
                        foreach (string number in line.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries))
                        {
                            intList.Add(Int32.Parse(number));
                        }
                    }
                }
            }
            return intList;
        }

Open in new window


Its a simple code which returns all numbers embedded in a List<int> Type of object...Then You can Iterate through this List<int> object to get individual numbers.. for example :
If you have a ListBox control named listBox1 and If you wish to populate this control with all the number items from a text file whose contents are like so :
1,2,3,4,5,6,7
22,33,45,67,88,
122,334,525,685,
I will enter the path of the file in a textbox control and pass TextBox1.Text in the above method..
ok then above method will be used like this inside a button click like so :
private void button1_Click(object sender, EventArgs e)
        {
            List<int> listDemo = GetIntegralValues(textBox1.Text);

            foreach (int no in listDemo)
            {
                listBox1.Items.Add(no);
            }
        }

Open in new window

0
 
Sat80Author Commented:
@FernandoSoto, thanks you are right, its working now. but the same old issue which is saving each number in one row. Can you please save the whole number in one row? the current output is (myInts):

1
2
3
4
5
6
7
8
9
10
11
12
5
4
6
8
1
2

Open in new window


And I would like to get this output (myInts):

1,2,3,4,5,6
7,8,9,10,11,12
5,4,6,8
1,2

Open in new window


Thanks again for the help, I really appreciate it :)

@kaufmed, yes each line has elements and they're divided by a comma (,)
0
 
Fernando SotoRetiredCommented:
Hi Sat80;

When you say you want to get this output :

1,2,3,4,5,6
7,8,9,10,11,12
5,4,6,8
1,2

Open in new window


This is a string representation and NOT integer value. Once the integers are stored in a array there is no way to know how many values were in the row they were in. Also if you want it in that format why change them to integers in the first place?

Can you explain what you need and what the end result needs to be?

Fernando
0
 
starlite551Commented:
Ok Finally I have some screen shots to make you understand what I was trying to explain you earlier : here take a look at these .. Windows Form Which Illustrates the above code
Code in Screenshot :
 Screen shot of code used in the form
0
 
starlite551Commented:
If you need comma seperated numbers printed in different lines from a text file It is possible .. But you need to save the contents in a List<string> Type of object like this method :
public List<string> GetIntegralValues(string txtFilePath)
        {
            List<string> strList = new List<string>();
            string content = "";
            using (FileStream fs = new FileStream(txtFilePath,FileMode.Open,FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    content = sr.ReadToEnd();

                    foreach (string line in content.Split(new string[]{"\n","\r"},StringSplitOptions.RemoveEmptyEntries))
                    {                        
                        strList.Add(line);
                    }
                }
            }
            return strList;
        }

Open in new window

0
 
starlite551Commented:
The use the above method like so :
foreach(string s in GetIntegralValues(@"C:\Users\Abc\Desktop\demo.txt"))
{
       Console.WriteLine(s);
}

Open in new window

0
 
Sat80Author Commented:
Hi FernandoSoto,

 

Thanks for your reply, I have an application that used the next array:

            int[][] s=

        {

           new[] { 1, 2, 3, 4, 5 },

            new[] { 1, 2, 3 },

            new[] { 1, 2 },

        };

 

What I want is that, I would like to get the array items for external file so I can change them easily without editing it manually from the source code. This is what I want to achieve. So, I want to save the array items to external file like this:

file.txt:

1, 2, 3, 4, 5

1, 2, 3

1, 2

 

And then read the txt file and insert the lines to array (s). I hope this is a clear example of what I want.

 

@starlite551, I really appreciate your help and code, I will test it as soon as I use my pc as I am submitting this comment via mobile thanks.
0
 
starlite551Commented:
OR Another Solution Would be Use the Same List<int> Type Method Like the previous one I showed you and use this code to get all the numbers printed in new lines but this time solution would be little complex.. the method's return type would be an ArrayList object instead of List<int> but this ArrayList object would individually contain two List<int> objects at indexes 0 and 1 respectively.. so my method would be like this :
public ArrayList GetIntegralValues(string txtFilePath)
        {
            ArrayList aList = new ArrayList();

            List<int> intList = new List<int>();
            string content = "";
            using (FileStream fs = new FileStream(txtFilePath,FileMode.Open,FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    content = sr.ReadToEnd();
                    int count = 0;
                    List<int> counterList = new List<int>();
                     
                    foreach (string line in content.Split(new string[]{"\n","\r"},StringSplitOptions.RemoveEmptyEntries))
                    {                        
                        counterList.Add(count);    
                        foreach (string number in line.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries))
                        {
                            count++; 
                            intList.Add(Int32.Parse(number));
                        }
                    }
                }
            }
            aList.Add(intList);
            aList.Add(counterList); 
            return aList;
        }

Open in new window


While retrieveing the values use this code then :
ArrayList aList = GetIntegralValues(@"C:\Users\Abc\Desktop\demo.txt");

List<int> listNumbers = ((List<int>)(aList[0]);
List<int> listNewLines = ((List<int>)(aList[1]);

for(i=0;i<listNumbers.Count;i++)
{
     Console.Write(listNumers[i].ToString()+",");
     if(listNewLines[i]==i)
     {
          Console.WriteLine("");
     }
}

Open in new window

0
 
starlite551Commented:
I am Starlite551 By the way not Fernando Sotto :)
0
 
starlite551Commented:
Sorry about that I missed a paranthesis in the above example :
ArrayList aList = GetIntegralValues(@"C:\Users\Abc\Desktop\demo.txt");

            List<int> listNumbers = ((List<int>)(aList[0]));
            List<int> listNewLines = ((List<int>)(aList[1]));

            StringBuilder sb = new StringBuilder();
            for(i=0;i<listNumbers.Count;i++)
            {
                 sb.Append(listNumers[i].ToString()+",");
                 if(listNewLines[i]==i)
                 {
                      listBox1.Items.Add(sb.ToString();
                 }
            }

Open in new window

0
 
starlite551Commented:
I dont know why but I think I made serious mistake in the method that returns an ArrayList here is the corrected Code :
public ArrayList GetIntegralValues2(string txtFilePath)
        {
            ArrayList aList = new ArrayList();

            List<int> intList = new List<int>();
            string content = "";
            List<int> counterList = new List<int>();

            using (FileStream fs = new FileStream(txtFilePath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    content = sr.ReadToEnd();
                    int count = 0;
                    
                    foreach (string line in content.Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        counterList.Add(count);
                        foreach (string number in line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            count++;
                            intList.Add(Int32.Parse(number));
                        }
                    }
                }
            }
            aList.Add(intList);
            aList.Add(counterList);
            return aList;
        }

Open in new window

And  
ArrayList aList = GetIntegralValues2(textBox1.Text);

            List<int> listNumbers = ((List<int>)(aList[0]));
            List<int> listNewLines = ((List<int>)(aList[1]));

            StringBuilder sb = new StringBuilder();
            for(int i=0;i<listNumbers.Count;i++)
            {
                 sb.Append(listNumbers[i].ToString()+",");
                 if(listNewLines[i]==i)
                 {
                      listBox1.Items.Add(sb.ToString());
                 }
            }

Open in new window

0
 
starlite551Commented:
change line 7 in the above code 2 to this :
for(int i=0;i<=listNumbers.Count;i++)

Open in new window

0
 
starlite551Commented:
Sorry about the errors.. in the above code.. I have debugged the code and removed all the errors now and here is an error free solution for you complete code that will make you happy :
public ArrayList GetIntegralValues2(string txtFilePath)
        {
            ArrayList aList = new ArrayList();

            List<int> intList = new List<int>();
            string content = "";
            List<int> counterList = new List<int>();

            using (FileStream fs = new FileStream(txtFilePath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    content = sr.ReadToEnd();
                    int count = 0;
                    
                    foreach (string line in content.Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries))
                    {                        
                        foreach (string number in line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            count++;
                            intList.Add(Int32.Parse(number));
                        }
                        counterList.Add(count);
                    }
                }
            }
            aList.Add(intList);
            aList.Add(counterList);
            return aList;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //List<int> listDemo = GetIntegralValues(textBox1.Text);
            //foreach (int no in listDemo)
            //{
            //    listBox1.Items.Add(no);
            //}

            ArrayList aList = GetIntegralValues2(textBox1.Text);

            List<int> listNumbers = ((List<int>)(aList[0]));
            List<int> listNewLines = ((List<int>)(aList[1]));

            StringBuilder sb = new StringBuilder();
            for(int i=0;i<listNumbers.Count;i++)
            {
                 sb.Append(listNumbers[i].ToString()+",");
                 for (int j = 0; j < listNewLines.Count; j++)
                 {
                     if (i == listNewLines[j])
                     {
                         listBox1.Items.Add(sb.ToString());
                     }    
                 }
                 
            }

        }

Open in new window

0
 
starlite551Commented:
I have again modified the Code to print the numbers in the listBox control :
ArrayList aList = GetIntegralValues2(textBox1.Text);

            List<int> listNumbers = ((List<int>)(aList[0]));
            List<int> listNewLines = ((List<int>)(aList[1]));

            StringBuilder sb = new StringBuilder();
            for(int i=0;i<listNumbers.Count;i++)
            {             
                 
                 for (int j = 0; j < listNewLines.Count; j++)
                 {
                     if (i == listNewLines[j])
                     {
                         listBox1.Items.Add(sb.ToString());
                         sb = new StringBuilder();
                     }
                     
                 }
                 sb.Append(listNumbers[i].ToString() + ",");
                 
            }
            listBox1.Items.Add(sb.ToString());

Open in new window

0
 
Fernando SotoRetiredCommented:
Hi Sat80;

As per your last post to me, this code snippet should give you what you want.

const string f = "TextFile1.txt";
const string o = "TextFileOuput1.txt";

char[] splitChars = new char[] { ',' };

List<int[]> listOfArray = new List<int[]>();
int[][] intArrayOfArray;

using (StreamReader r = new StreamReader(f))
{
    string line;
    // Read each line of the file and convert strings to array of int's
    // Place array of int's into List<int[]>
    while ((line = r.ReadLine()) != null)
    {
        List<int> data = new List<int>();
        line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(i => { data.Add(Convert.ToInt32(i)); });
        listOfArray.Add(data.ToArray());
    }
}

// Convert List of array's of ints into an array of array of ints
intArrayOfArray = listOfArray.ToArray();

// Modify the data that is in the intArrayOfArray as needed
// Then save to the file system.

// Convert the int[][] intArrayOfArray to comma separated values in the 
// same for mat as before.
using( StreamWriter w = new StreamWriter(o))
{
    System.Text.StringBuilder outLine = new System.Text.StringBuilder();
    foreach(int[] wdata in intArrayOfArray)
    {
        outLine.Length = 0;
        wdata.ToList().ForEach( d => outLine.Append( d.ToString() + ","));
        w.WriteLine(outLine.Remove(outLine.Length - 1, 1).ToString());
    }
}

Open in new window


Fernando
0
 
Sat80Author Commented:
Dear ALL,

I would like to thank you all for all the help, and I will award you for the previous help. But I really want only thing I might not ask it clear before. I am using C# 2008 console application.
The final result I want is that:
file.txt:
1, 2, 3, 4, 5

1, 2, 3

1, 2

Open in new window


and I want to load the previous file as shown next:

 int[][] s= (the txt file lines, each line as one row)

Open in new window


So, if we already load the file lines then the previous array ( int[][] s) will have the next items:
            int[][] s=

        {

           new[] { 1, 2, 3, 4, 5 },

           new[] { 1, 2, 3 },

           new[] { 1, 2 },

        };

Open in new window


I hope the final result is clear and sorry again for all those questions :)
Regards
0
 
Fernando SotoRetiredCommented:
Please answer the following two questions.

1.  What does the input file look like? Please give sample.
2.  What is the result file look like? Given the input file from question 1 give sample of what you want written to the file.
0
 
Sat80Author Commented:
Hi,
1- The input file looks like this:
1, 2, 3, 4, 5

1, 2, 3

1, 2

Open in new window


2- the result will not be written to a text file. but the result will be load to an array:
int[][] s

So, the idea is to load the file lines (from answer 1) to the integer (in answer 2). The result when load the file in answer one is that:
   int[][] s=

        {

           new[] { 1, 2, 3, 4, 5 },

           new[] { 1, 2, 3 },

           new[] { 1, 2 },

        };

Open in new window


Because the first item on the array is:
 new[] { 1, 2, 3, 4, 5 },
which is the first line of the text file (in answer one) and so on.

==========

Another example:
1- The input file looks like this:
2,2,2

3,3

4,4,4

Open in new window


2- the result will not be written to a text file. but the result will be load to an array:
int[][] s

So, the idea is to load the file lines (from answer 1) to the integer (in answer 2). The result when load the file in answer one is that:
   int[][] s=

        {

           new[] { 2,2,2},

           new[] { 3,3 },

           new[] { 4,4,4},

        };

Open in new window


I hope I have explained it clearly. Thanks for the help.
0
 
Fernando SotoRetiredCommented:
Hi Sat80;

If you go over my post ID: 34946906 above and use the lines 1 through 23 it will give you what you are asking for. Line 23 the variable intArrayOfArray is of type int[][] with all lines filled in.

Fernando
0
 
Sat80Author Commented:
Hi Fernando,
Yes you are right, and please excuse me for the misunderstanding as I am still beginner in c#, thanks for all the help:)
Regards
0
 
Sat80Author Commented:
Thank you ALL, and sry I wish I had more than 500 points to give you all:)
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 11
  • 9
  • 7
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now