The Lightkeeper
The Lightkeeper

Reputation: 1

putting a string of numbers in an array

I'm trying to receive an integer of 40 characters as a string from the console and iterate over each element in that string and then save it as an element in an array of int's. this is not working and just returns 49 50 51 as array members.

public HugeInteger(string myString)
{
    for (int i = 0; i < 39; i++)
    {
        int t = Convert.ToInt16(myString[i]);
        this.myInteger[i] = t;
    }
}

Upvotes: 0

Views: 486

Answers (5)

Matthew Watson
Matthew Watson

Reputation: 109567

Since you are trying to convert chars '0' .. '9' to integers, you just need to subtract the character code for '0' from each character, like so:

public HugeInteger(string myString)
{
    for (int i = 0; i < 39; i++)
    {
        char c = myString[i]; 

        // Remove the next `if` (and its body) if error checking is not required.

        if (c < '0' || c > '9')
            throw new InvalidOperationException("Non-digit in input");

        this.myInteger[i] = c - '0';
    }
}

This works because:

  1. The character codes for '0' to '9' are 48 .. 57
  2. If you subtract '0' from a character code, you are effectively subtracting 48 from it.
  3. Therefore subtracting '0' from a digit character will yield the int equivalent.

Note that there is no error checking in your loop, so if the string contains any non-digit characters, the result will be wrong!

Upvotes: 4

J-school
J-school

Reputation: 19

static void Main(string[] args)
        {
            Console.WriteLine("Input number");
            string myStr = Console.ReadLine();
            int[] intNums = new int[40];
            string flag = "";

            for (int i = 0; i < myStr.Length; i++)
            {

                int a = 1;
                flag = myStr.Substring(i, a);
                a = i;
                intNums[i] = Convert.ToInt32(flag);
                a = i;

            }

            foreach (var item in intNums)
            {

                if (item > 0)
                {
                    Console.Write(item+",");
                }

            }
            Console.ReadKey();
        }

IF you take an input you should sub-string the string, convert each part to an int, and then store in the array. Not sure a 40 character long integer would work just with the number bits even int64 can handle

Upvotes: -1

MDT
MDT

Reputation: 1695

If you want the string to be converted to an array i would suggest that you convert the string to char array and then convert back to int[] like below:

class Program
    {
        static void Main(string[] args)
        {
            string myString = "1231654165152112315461561561651561562165";
            var charArray = myString.ToCharArray();
            foreach (var item in charArray)
            {
                Console.WriteLine(item);

            }
            int[] myStringIntegers = Array.ConvertAll(charArray, c => (int)Char.GetNumericValue(c));
            Console.WriteLine(myStringIntegers.Length);

            int i = 0;
            foreach (var item in myStringIntegers)
            {
                Console.WriteLine("Value at pos("+i+") : " + item);
                i++;
            }
            Console.Read();
        }
    }

if you have multi digit numbers then i would say that you have the myString value separated by a comma ',' or space or whatever you like.

CAUTION : If the value is non-numeric then it will result in code failure. So you need to make a regex check or some sort of validation to address non-numeric inputs

Upvotes: 1

Mohammad Niazmand
Mohammad Niazmand

Reputation: 1547

If your input is like this :

"1 2 3 4"

You should split it with ' ' or else you should separate your numbers with a separator.

        List<int> myInteger=new List<int>();
        public void HugeInteger(string myString)
        {
            foreach (string value in myString.Split(' '))
            {
                myInteger.Add(int.Parse(value));
            }

        }

Without seperator you should iterate by this way:

    foreach (char c in myString)
    {
        myInteger.Add(int.Parse(c.ToString()));
    }

Upvotes: 0

jegtugado
jegtugado

Reputation: 5141

Below is 2 simple ways of extracting an array of integers from a string.

  1. Converting char to int.
  2. Converting a split string to int.

This may not be the best or most elegant solution but you can get some idea on how you would want to approach your problem.

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Input str: ");
        string str = Console.ReadLine();
        int[] numbers = StringToIntArray(str);
        foreach(int num in numbers)
        {
            Console.WriteLine(num);
        }
        Console.Write("Input str: ");
        str = Console.ReadLine();
        Console.Write("Input split char: ");
        ConsoleKeyInfo splitChar = Console.ReadKey();
        numbers = StringToIntArray(str, splitChar.KeyChar);
        Console.WriteLine();
        foreach (int num in numbers)
        {
            Console.WriteLine(num);
        }
        Console.ReadKey();
    }

    public static int[] StringToIntArray(string str, char? splitChar = null)
    {
        List<int> numbers = new List<int>();


        if (splitChar.HasValue)
        {
            string[] split = str.Split(splitChar.Value);

            foreach(string splitStr in split)
            {
                int parsedInt = 0;

                if (int.TryParse(splitStr, out parsedInt))
                {
                    numbers.Add(parsedInt);
                }
            }
        }
        else
        {
            foreach (char c in str)
            {
                int parsedInt = 0;

                if (int.TryParse(c.ToString(), out parsedInt))
                {
                    numbers.Add(parsedInt);
                }
            }
        }            

        return numbers.ToArray();
    }
}

Output: enter image description here

Upvotes: 0

Related Questions