简体   繁体   中英

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.

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM