C# 将空格分隔的字节数组整数转换为整数列表
本文关键字:整数 数组 转换 列表 字节数 字节 空格 分隔 | 更新日期: 2023-09-27 18:37:21
我有以下数字,我在控制台中输入一行空格:
4 20 3 3 1
我读了这一行并将其分配给一个字符串变量。使用ASCIIEncoding.ASCII.GetBytes()我将字符串转换为字节数组。
如何通过删除空格并将整数添加到列表中来将字节数组拆分为整数?
例如,上述数字将转换为列表[4, 20, 3, 3, 1]。

您可以在输入字符串上调用.Split(" "),您将获得所需的字符串数组。
而不是您需要将它们转换为 int。如果您确定您的输入以这种方式出现,则可以使用 linq:
string[] split = input.Split(" ");
List<int> values = split.Select(x => int.Parse(x)).ToList();
使用 Linq:
static void Main(string[] args)
{
var input = Console.ReadLine();
var integers = input.Split(new Char[] { ' ' }).Select(x => Convert.ToInt32(x)).ToList();
}
编辑:添加了以byte[]作为唯一问题参数的解决方案
我不知道为什么你不能只拿你的字符串来完成事情,但这里有一个解决方案,其中包含该字符串的 ascii 符号的字节数组。请注意任何其他非数字或空格字符和 int32 溢出。
List<byte[]> splitResult = new List<byte[]>();
IEnumerable<byte> bytes = new byte[] { (byte)'1', (byte)'2', (byte)' ', (byte)'5', (byte)'4', (byte)' ', (byte)' ' }; // <- this should be your bytes
while (bytes.Any())
{
byte[] oneNumberBytes = bytes.SkipWhile(x => x == ' ').TakeWhile(x => x != ' ').ToArray();
if(oneNumberBytes.Count() > 0) splitResult.Add(oneNumberBytes);
bytes = bytes.SkipWhile(x => x == ' ').SkipWhile(x => x != ' ');
}
var result = splitResult.Select(sr => sr.Aggregate(0, (seed, asciiDigit) => seed * 10 + asciiDigit - '0')).ToList();
如果可以恢复初始字符串:
使用string.Split方法。
Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToList();