You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将含两个-1终止符的输入拆分至两个数组

C# 实现指定规则整数输入拆分方案

核心处理逻辑

整个处理流程不需要提前预知输入总长度,按顺序遍历解析即可:

  • 逐段读取键盘输入,把所有输入内容解析为整数序列,自动忽略多余空格、换行符
  • 第一阶段收集资产三元组:按顺序每3个整数为一组,映射为type/value/amount资产属性,直到遇到第一个终止符-1时结束第一阶段
  • 第二阶段收集第二段整数:从第一个-1的下一个位置开始逐个收集整数,直到遇到第二个终止符-1时结束全部处理
  • 增加基础合法性校验:第一阶段收集的整数数量必须是3的整数倍,否则判定为输入格式不符合规则

完整实现代码

// 定义资产三元组结构,C# 9及以上版本可直接使用record,低版本可替换为class或struct
public record Asset(int Type, int Value, int Amount);

public static void InputProcessor()
{
    // 存储解析出的所有整数
    List<int> allNumbers = new List<int>();
    Console.WriteLine("请按规则输入整数序列:");
    
    // 读取输入,兼容多行输入场景
    string? inputLine;
    while (!string.IsNullOrEmpty(inputLine = Console.ReadLine()))
    {
        var segments = inputLine.Split(new[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
        foreach (var seg in segments)
        {
            if (int.TryParse(seg, out int num))
            {
                allNumbers.Add(num);
            }
        }
        // 读到两个终止符-1即可提前终止读取,无需等待额外输入
        if (allNumbers.Count(n => n == -1) >= 2)
        {
            break;
        }
    }

    // 初始化两个结果存储容器
    List<Asset> assetList = new List<Asset>();
    List<int> secondSection = new List<int>();
    
    int currentIndex = 0;
    // 第一阶段:解析资产三元组
    while (currentIndex < allNumbers.Count)
    {
        int currentNum = allNumbers[currentIndex];
        if (currentNum == -1)
        {
            currentIndex++;
            break;
        }
        // 校验剩余数字长度是否足够凑成一组三元组
        if (currentIndex + 2 >= allNumbers.Count)
        {
            throw new InvalidDataException("第一部分资产数据长度不合法,有效数字长度必须为3的倍数");
        }
        int type = allNumbers[currentIndex];
        int value = allNumbers[currentIndex + 1];
        int amount = allNumbers[currentIndex + 2];
        assetList.Add(new Asset(type, value, amount));
        currentIndex += 3;
    }

    // 第二阶段:解析第二段整数集合
    while (currentIndex < allNumbers.Count)
    {
        int currentNum = allNumbers[currentIndex];
        if (currentNum == -1)
        {
            break;
        }
        secondSection.Add(currentNum);
        currentIndex++;
    }

    // 以下为测试输出,实际使用可替换为对应业务逻辑
    Console.WriteLine("解析到的资产集合:");
    foreach (var asset in assetList)
    {
        Console.WriteLine($"({asset.Type},{asset.Value},{asset.Amount})");
    }
    Console.WriteLine("解析到的第二段整数集合:");
    Console.WriteLine(string.Join(",", secondSection));
}

效果验证

针对示例输入1 500 5 2 25 100 3 10 50 -1 3 9 -1,运行上述代码输出结果如下:

解析到的资产集合:
(1,500,5)
(2,25,100)
(3,10,50)
解析到的第二段整数集合:
3,9

完全符合预期拆分要求。代码兼容多行输入、输入夹带多余空格/制表符的场景,遇到不符合规则的输入会抛出明确的异常提示。

内容的提问来源于stack exchange,提问作者StarTeker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 00:21:39