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

如何一次性将文本框中的多个数字添加到C#数组中?

解决文本框多数字解析并存入数组的问题

原代码的核心问题是直接尝试将文本框的全部内容解析为单个整数,当输入多个空格分隔的数字时,整个字符串不是合法整数,自然解析失败;另外循环里的break也导致只尝试处理一次,无法遍历多个数字。

以下是修复后的代码:

namespace Time4
{
    public partial class Form1 : Form
    {
        int[] numbers = new int[10];
        int currentIndex = 0; // 记录数组当前填充的位置

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 清空之前的结果和数组索引,避免重复累加
            richTextBox1.Text = "";
            currentIndex = 0;

            // 将文本框内容按空格分割,过滤掉空字符串(处理连续空格的情况)
            string[] inputParts = textBox1.Text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

            foreach (string part in inputParts)
            {
                // 遍历每个分割后的字符串,尝试解析为整数
                if (int.TryParse(part, out int parsedNum) && currentIndex < numbers.Length)
                {
                    // 存入数组
                    numbers[currentIndex] = parsedNum;
                    // 输出计算结果
                    richTextBox1.Text += parsedNum * 4 + Environment.NewLine;
                    currentIndex++;
                }
            }
        }
    }
}

关键修改点说明:

  • 使用Split方法将输入文本按空格分割成单个数字字符串,StringSplitOptions.RemoveEmptyEntries可以自动忽略连续空格产生的空元素
  • 用foreach遍历每个分割后的字符串,逐个解析为整数,避免一次性解析整个文本
  • 增加currentIndex变量跟踪数组的填充位置,防止数组越界
  • 每次点击按钮时清空之前的结果和索引,避免重复数据累加

如果想要更灵活的存储(比如不限制10个数字),可以把int[] numbers换成List<int>,代码调整如下:

List<int> numbers = new List<int>();

// 存入数组的部分替换为:
numbers.Add(parsedNum);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:14:58