[英]Split input with two termination numbers into two arrays c#
Lets assume we have an input from keyboard.假设我们有来自键盘的输入。
I dont know the length of the input, but I know that the first part is an array of integers, where consecutive groups of three numbers describe assets: type,value,amount
.我不知道输入的长度,但我知道第一部分是一个整数数组,其中连续的三个数字组描述资产: type,value,amount
。
then termination number is -1
then I have another array of integers and then again termination number -1
然后终止号为-1
,然后我有另一个整数数组,然后再次终止号-1
For example:例如:
1 500 5 2 25 100 3 10 50 -1 3 9 -1
So I want to have 2 containers to work with first is {(1,500,5),(2,25,100),(3,10,50)}
and second is {3,9}
.所以我想有 2 个容器可以使用,第一个是{(1,500,5),(2,25,100),(3,10,50)}
,第二个是{3,9}
。
How I can make this happen?我怎样才能做到这一点?
This will give you a List of structs containing the asset data triples from the first part of the string, and an array of ints from the second part:这将为您提供一个结构列表,其中包含来自字符串第一部分的资产数据三元组,以及来自第二部分的整数数组:
public struct assetData {
public int type;
public int value;
public int amount;
};
void Main()
{
string keyboard = "1 500 5 2 25 100 3 10 50 -1 3 9 -1";
string[] parts = keyboard.Split("-1", StringSplitOptions.RemoveEmptyEntries);
int[] assetInput = parts[0].Trim().Split().Select(int.Parse).ToArray();
int[] numbers = parts[1].Trim().Split().Select(int.Parse).ToArray();
// take 3 numbers at a time into assetData structs. Store them.
var assetInfo = new List<assetData>();
for (int i = 0; i < assetInput.Length; i += 3)
{
assetData item;
item.type = assetInput[i];
item.value = assetInput[i+1];
item.amount = assetInput[i+2];
assetInfo.Add(item);
}
}
variant for array input:数组输入的变体:
public struct assetData {
public int type;
public int value;
public int amount;
};
void Main()
{
string keyboard = "1 500 5 2 25 100 3 10 50 -1 3 9 -1";
int[] input = keyboard.Trim().Split().Select(int.Parse).ToArray();
// 3 numbers at a time into assetData structs. Store them.
var assetInfo = new List<assetData>();
int i;
for (i=0; input[i] != -1; i += 3)
{
assetData item;
item.type = input[i];
item.value = input[i+1];
item.amount = input[i+2];
assetInfo.Add(item);
}
i++; // skip the -1
var numbers = new List<int>();
while (i < input.Length - 1) {
numbers.Add(input[i]);
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.