Muhammad Ali Dildar
Muhammad Ali Dildar

Reputation: 1527

How to convert char array into int?

I am taking input from a text box. I've saved the input digits from text box to an array like this:

char[] _array = textBox1.Text.ToCharArray(0, textBox1.Text.Length);

Now I want to convert the array to an int array because I want to perform mathematical operations on each index of the array.

How can I achieve the goal? Thanks.

Upvotes: 3

Views: 15930

Answers (4)

Muhammad Ali Dildar
Muhammad Ali Dildar

Reputation: 1527

I've solved my problem. I used list to accomplish the task.

I stored each array index at the relative index of the list after converting each index value to int.

Using list seems more convenient way to me. :)

Thanks to all of you.

Upvotes: 1

Eric K Yung
Eric K Yung

Reputation: 1784

If each character expected to be a digit, you can parse it to an int:

List<int> listOfInt = new List<int>();
_array.ToList().ForEach(v => listOfInt.Add(int.Parse(v.ToString())));
int[] _intArray = listOfInt.ToArray();

Character code value:

List<int> listOfCharValue = new List<int>();
_array.ToList().ForEach(v => listOfCharValue.Add((int)v));
int[] _charValueArray = listOfCharValue.ToArray();

You need to handle exceptions.

Upvotes: 6

Maess
Maess

Reputation: 4146

Assuming what I asked in my comment is true:

string[] ints = { "1", "2", "3" };

var str = ints.Select(i => int.Parse(i));

However, the above will work only if you have already validated that your input from the text box is numeric.

Upvotes: 1

Bryan Crosby
Bryan Crosby

Reputation: 6554

You could do it with LINQ if you just want the character code of each char.

var intArrayOfText = "some text I wrote".ToCharArray().Select(x => (int)x);

or

var intArrayOfText = someTextBox.Text.ToCharArray().Select(x => (int)x);

Upvotes: 10

Related Questions