Parse string to int array

13,157

Solution 1

Wrong brackets, to access the character within string.

d[2] = Convert.ToInt32(Convert.ToString(s(1)));
                                         ^

Use,

d[2] = Convert.ToInt32(Convert.ToString(s[1]));

Solution 2

 var intArr =  "12345678".Select(c => (int)(c-'0')).ToArray();

Solution 3

Try this:-

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

Solution 4

Can be done like this , if the string is like below

        string temps = "-5 8 4 0 1 17 25 -5 -3";
        int[] integerArray = temps.Split(' ').Select(x => int.Parse(x)).ToArray();
        Array.Sort(integerArray);
        foreach (var item in integerArray)
        {
            Console.WriteLine(item);
        }
Share:
13,157
Marshal
Author by

Marshal

Foresic Computing student at the University of the West of England. I have some knowledge of Java however am focusing now on C#.

Updated on June 07, 2022

Comments

  • Marshal
    Marshal almost 2 years

    Hi there I am working on increasing my knowledge of C# and I want to do a simple task but am finding it difficult.

    I want to parse each character of a string to an int array.

        int[] d = new int[10];
         private void button1_Click(object sender, EventArgs e)
        {
            s = textBox1.Text;
    
            d[2] = Convert.ToInt32(Convert.ToString(s[1]));
            d[3] = Convert.ToInt32(Convert.ToString(s[2]));
            d[4] = Convert.ToInt32(Convert.ToString(s[3]));
            d[5] = Convert.ToInt32(Convert.ToString(s[4]));
            .....
    

    I know the code is wrong but I wanted to show an example. Have looked at Google for the past hour but have found people wanting to display characters in new lines and using if statements to parse. I want something similar to above. Can this be done? Thank you for your time.

    I found this line of code in Java which is exactly what I want to do but is there an equivilant?

        d1 = Integer.parseInt(String.valueOf(s.charAt(0)));
    

    I now have a new problem that when i submit a number no matter how many numbers i put in it will come back with "Index was outside the bounds of the array."

    I also need to limit it to 10 integers in the array d.

  • Henk Holterman
    Henk Holterman over 11 years
    (int)'0' does not produce 0.
  • Rahul Tripathi
    Rahul Tripathi over 11 years
    Thanx for that. Updated my answer as well
  • Marshal
    Marshal over 11 years
    Comes back with an error "Index was outside the bounds of the array." but thank you for pointing that one out.
  • Anirudh Ramanathan
    Anirudh Ramanathan over 11 years
    Is the Textbox.text empty? Index is outside, only if the index you are giving is greater than the string length