简体   繁体   English

将数字字符串拆分为数字并发送到数组

[英]Split string of numbers into digits and send to array

I want to split a 40 digit number and send each digit into an array called digits. 我想分割一个40位数字,并将每个数字发送到一个称为数字的数组中。 ToArray doesn't work because it can't convert from char to int. ToArray不起作用,因为它无法从char转换为int。 Neither does Split I think? 我也不认为斯普利特吗? I'm stumped 我很困惑

edit: These are the instructions: Create a class HugeInteger which uses a 40-element array of digits to store integers as large as 40 digits each. 编辑:这些是指令:创建一个HugeInteger类,该类使用40个元素的数字数组来存储每个最大为40位数字的整数。 Provide methods Input, ToString, Add and Subtract. 提供方法Input,ToString,Add和Subtract。 For comparing HugeInteger objects, provide the following methods: IsEqualTo, IsNotEqualTo, IsGreaterThan, IsLessThan, IsGreaterThanOrEqualTo and IsLessThanOrEqualTo. 为了比较HugeInteger对象,请提供以下方法:IsEqualTo,IsNotEqualTo,IsGreaterThan,IsLessThan,IsGreaterThanOrEqualTo和IsLessThanOrEqualTo。 Each of these is a method that returns true if the relationship holds between the two HugeInteger objects and returns false if the relationship does not hold. 每个方法都是一个方法,如果两个HugeInteger对象之间的关系成立,则返回true;如果关系不成立,则返回false。 Provide method IsZero. 提供方法IsZero。 In the Input method, use the string method ToCharArray to convert the input string into an array of characters, then iterate through these characters to create your HugeInteger. 在Input方法中,使用字符串方法ToCharArray将输入字符串转换为字符数组,然后遍历这些字符以创建HugeInteger。

string digits = "8957853759876839473454789595495735984339";
int[] array = digits.Select(x => (int)char.GetNumericValue(x)).ToArray();

Or 要么

int[] array = digits.Select(x => x - 48).ToArray();

As @Haldo requested explanation about why this one should work, It is because char is implicitly castable to int. 正如@Haldo要求解释为什么该方法应该工作的原因是,因为char隐式可转换为int。 Live Demo 现场演示

If you want to avoid getting Exception if there are characters that can not be parsed as numbers, you may ignore them: 如果要避免在某些字符不能解析为数字的情况下获得Exception,则可以忽略它们:

int[] array = digits.Where(x => char.IsNumber(x)).Select(x => x - 48).ToArray();

You can use Select extension method to transform the characters into integers: 您可以使用Select扩展方法将字符转换为整数:

int[] result = str.Select(x => int.Parse(x.ToString()))
                  .ToArray();

or assuming there could be invalid characters: 或假设可能存在无效字符:

int[] result = str.Where(char.IsDigit)
                  .Select(x => int.Parse(x.ToString()))
                  .ToArray();

To handle huge number the best way is to convert string of integers to an array of bytes. 要处理大量数字,最好的方法是将整数字符串转换为字节数组。 So code converts the decimal number to binary byte[] array. 因此,代码将十进制数转换为二进制byte []数组。 Is uses the method that is taught in school to do base conversion from decimal to hex using long division. 是使用学校教的方法使用长除法进行从十进制到十六进制的基数转换。

I tested code thoroughly by using every number between 0 and 2^24. 我使用0到2 ^ 24之间的每个数字对代码进行了彻底的测试。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication89
{
    class Program
    {
        static void Main(string[] args)
        {

            string digits = "8957853759876839473454789595495735984339";
            List<byte> results = Binary.GetBytes(digits);
            //test code
            //for (int i = 0; i < (Math.Pow(2,24)); i++)
            //{
            //    string digits = i.ToString();
            //    Console.WriteLine(i);
            //    List<byte> results = Binary.GetBytes(digits);
            //    long value = results.Select((x, j) => x << (j * 8)).Sum();
            //    if (i != value)
            //    {
            //        int a = 3;
            //    }
            //}
        }


    }
    public class Binary
    {
        public static List<byte> GetBytes(string input)
        {
            List<byte> results = new List<byte>();
            string divisorStr = input;


            int nibbleCount = 0;


            while (divisorStr.Length != 0)
            {
                int number = 0;
                string quotentStr = "";
                byte carry = 0;

                //divide a string by 16 to get remainders
                while (divisorStr.Length != 0)
                {
                    number = (carry * 10) + int.Parse(divisorStr.Substring(0, 1));
                    divisorStr = divisorStr.Substring(1);
                    if (divisorStr.Length == 0) exit = true;

                    int digit = number / 16;
                    if (quotentStr != "" | (digit != 0))
                    {
                        quotentStr += digit.ToString();
                    }
                    carry = (byte)(number % 16);
                }
                ///combine the remainders together into an array of bytes
                if (nibbleCount % 2 == 0)
                {
                    results.Add(carry);
                }
                else
                {
                    results[results.Count - 1] |= (byte)(carry << 4);
                }
                divisorStr = quotentStr;
                nibbleCount++;
            }
            return results;
        }
    }
}

Since you want it into just a char array, why not just call .ToString() on the int then call .ToCharArray() ? 由于您只想将其放入一个char数组中,为什么不直接在int上调用.ToString()然后再调用.ToCharArray()呢?

 int nums = 123456789; char[] numss = nums.ToString().ToCharArray(); foreach(char n in numss) { Console.Write(string.Format("{0} ", n)); } // 1 2 3 4 5 6 7 8 9... 

Since I misread the question and everybody is using the Select extension, why not just use a simple for loop and convert them to int . 由于我误解了问题,并且每个人都在使用Select扩展名,为什么不使用简单的for循环并将其转换为int

string nums = "12345";
int [] digits = new int[nums.Length];

for(int i = 0; i < nums.Length; i++) {
    digits[i] = Convert.ToInt32(Char.GetNumericValue(nums[i]));
}

foreach(int n in digits) {
    Console.Write(string.Format("{0} ", n));
}
// 1 2 3 4 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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