Solved

Convert string to Integer

Posted on 2011-02-21
31
1,079 Views
Last Modified: 2013-12-17
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
Comment
Question by:Sat80
  • 11
  • 9
  • 7
  • +3
31 Comments
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 20 total points
ID: 34945419
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 34945440
What does the input file look like? Can you post a sample.
0
 
LVL 7

Assisted Solution

by:50cal
50cal earned 20 total points
ID: 34945472
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
 

Author Comment

by:Sat80
ID: 34945474
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 34945739
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
 
LVL 6

Assisted Solution

by:TinTombStone
TinTombStone earned 50 total points
ID: 34945853
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
 

Author Comment

by:Sat80
ID: 34945866
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
 

Author Comment

by:Sat80
ID: 34945907
@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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 34945952
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 34945956
Make sure you have the using statement

using System.Linq;
0
 
LVL 12

Expert Comment

by:starlite551
ID: 34946039
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
 

Author Comment

by:Sat80
ID: 34946059
@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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 34946154
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
 
LVL 12

Expert Comment

by:starlite551
ID: 34946159
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
 
LVL 12

Expert Comment

by:starlite551
ID: 34946209
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 12

Expert Comment

by:starlite551
ID: 34946232
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
 

Author Comment

by:Sat80
ID: 34946327
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
 
LVL 12

Expert Comment

by:starlite551
ID: 34946361
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
 
LVL 12

Expert Comment

by:starlite551
ID: 34946373
I am Starlite551 By the way not Fernando Sotto :)
0
 
LVL 12

Expert Comment

by:starlite551
ID: 34946459
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
 
LVL 12

Expert Comment

by:starlite551
ID: 34946493
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
 
LVL 12

Expert Comment

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

Open in new window

0
 
LVL 12

Expert Comment

by:starlite551
ID: 34946667
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
 
LVL 12

Assisted Solution

by:starlite551
starlite551 earned 205 total points
ID: 34946750
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
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 205 total points
ID: 34946906
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
 

Author Comment

by:Sat80
ID: 34947820
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 34948018
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
 

Author Comment

by:Sat80
ID: 34948059
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 34948154
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
 

Author Comment

by:Sat80
ID: 34950072
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
 

Author Closing Comment

by:Sat80
ID: 34950129
Thank you ALL, and sry I wish I had more than 500 points to give you all:)
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now