Solved

# Convert string to Integer

Posted on 2011-02-21
1,090 Views
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?

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.
{
// 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.
}
}

// 5
// Print out all the lines.
foreach (string s in lines)
{
Console.WriteLine(s);
}
}
}
``````
0
Question by:Sat80
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 11
• 9
• 7
• +3

LVL 75

Assisted Solution

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
{
}
catch  // You'll want to catch a specific exception.
//  I think the proper exception is InvalidFormatException
{
// Found invalid number
}
``````
0

LVL 63

Expert Comment

ID: 34945440
What does the input file look like? Can you post a sample.
0

LVL 7

Assisted Solution

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

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 63

Expert Comment

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.
{
// 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());
}
``````

Fernando
0

LVL 6

Assisted Solution

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.
{
// 3
// Use while != null pattern for loop
string line;
while ((line = r.ReadLine()) != null)
{
string[] words = line.Split(',');
foreach (string word in words)
{
}
}
}

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

}
}
0

Author Comment

ID: 34945866
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?)
``````
0

Author Comment

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 75

Expert Comment

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 63

Expert Comment

ID: 34945956
Make sure you have the using statement

using System.Linq;
0

LVL 12

Expert Comment

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))
{
{
sr.BaseStream.Seek(0, SeekOrigin.Begin);

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

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)
{
}
}
``````
0

Author Comment

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
``````

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
``````

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

@kaufmed, yes each line has elements and they're divided by a comma (,)
0

LVL 63

Expert Comment

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
``````

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

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 ..
Code in Screenshot :

0

LVL 12

Expert Comment

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))
{
{
sr.BaseStream.Seek(0, SeekOrigin.Begin);

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

LVL 12

Expert Comment

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

Author Comment

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

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))
{
{
sr.BaseStream.Seek(0, SeekOrigin.Begin);
int count = 0;
List<int> counterList = new List<int>();

foreach (string line in content.Split(new string[]{"\n","\r"},StringSplitOptions.RemoveEmptyEntries))
{
foreach (string number in line.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries))
{
count++;
}
}
}
}
return aList;
}
``````

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("");
}
}
``````
0

LVL 12

Expert Comment

ID: 34946373
I am Starlite551 By the way not Fernando Sotto :)
0

LVL 12

Expert Comment

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)
{
}
}
``````
0

LVL 12

Expert Comment

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))
{
{
sr.BaseStream.Seek(0, SeekOrigin.Begin);
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++;
}
}
}
}
return aList;
}
``````
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)
{
}
}
``````
0

LVL 12

Expert Comment

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

LVL 12

Expert Comment

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))
{
{
sr.BaseStream.Seek(0, SeekOrigin.Begin);
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++;
}
}
}
}
return aList;
}
private void button1_Click(object sender, EventArgs e)
{
//List<int> listDemo = GetIntegralValues(textBox1.Text);
//foreach (int no in listDemo)
//{
//}

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])
{
}
}

}

}
``````
0

LVL 12

Assisted Solution

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])
{
sb = new StringBuilder();
}

}
sb.Append(listNumbers[i].ToString() + ",");

}
``````
0

LVL 63

Accepted Solution

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;

{
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)); });
}
}

// 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());
}
}
``````

Fernando
0

Author Comment

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
``````

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

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

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 },

};
``````

I hope the final result is clear and sorry again for all those questions :)
Regards
0

LVL 63

Expert Comment

ID: 34948018

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

ID: 34948059
Hi,
1- The input file looks like this:
``````1, 2, 3, 4, 5

1, 2, 3

1, 2
``````

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 },

};
``````

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
``````

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},

};
``````

I hope I have explained it clearly. Thanks for the help.
0

LVL 63

Expert Comment

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

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

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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
###### Suggested Courses
Course of the Month6 days, 18 hours left to enroll