3

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.

4
  • 2
    We need to know your intention here. Are you expecting a string of numerical values or do you want to convert each char to its character code? Commented Nov 15, 2011 at 19:32
  • Have you implemented code to make sure that the text box input is numeric? You code above is just converting each character in the text box to its numberic CHAR value is that your intent, or do you want to convert the input string to an int ie "1234" to 1234? Commented Nov 15, 2011 at 19:39
  • I want to get numerical value. Each digit at particular index of array respectively. Commented Nov 15, 2011 at 19:40
  • @Maess- I've put a check over key event so that the text box would allow only numerical values. Commented Nov 15, 2011 at 19:42

4 Answers 4

10

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice use of LINQ :)
6

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.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.