【问题标题】:c# windows application arrays and string split [closed]c# windows 应用程序数组和字符串拆分 [关闭]
【发布时间】:2014-09-01 01:23:11
【问题描述】:

我正在尝试在 C# 中拆分字符串并使用以下代码:

string str = Encoding.ASCII.GetString(e.Data);
string[] words = str.Split(' '.ToArray());

但我在Split(' '.ToArray());有一个错误我想拆分文本并将其保存为数组,例如我有:

string input = '1 2 3 4 5 6 7';

要成为的数组:

string[] array = input.split(' ');
output:
array[0] = 1
array[1] = 2 ....

我尝试过这种方法,但它们不起作用我不知道为什么。

来自异常的消息是:"index was outside the bounds of the array"

所有代码如下:

void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
        {
            if (this.InvokeRequired)
            {
                // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
                this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e });
                return;
            }

            int maxTextLength = 1000; // maximum text length in text box
            if (tbData.TextLength > maxTextLength)
                tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength);

            // This application is connected to a GPS sending ASCCI characters, so data is converted to text
            string str = Encoding.ASCII.GetString(e.Data);
            //tbData.AppendText(str);
            //tbData.ScrollToCaret();

            string[] words = str.Split();

            try
            {
                tbData.Text = words[1].ToString();
            }
            catch (Exception ex)
            { 
                MessageBox.Show(ex.Message);
            }

            richD.AppendText(str);
            richD.ScrollToCaret();

        }

希望您能提供帮助。 或者如果您有更好的想法将接收到的数据插入 datagridview

【问题讨论】:

  • Split 方法将返回字符串[]。你的问题是什么。行 str.Split(' '.ToArray());也错了。
  • 您收到的异常似乎表明您的str 没有价值。您是否在调试器中验证了 str 实际上有一个值?
  • 好的,那么编辑中的完整代码如何与您最初寻求帮助时发布的部分代码匹配?你的问题是“我在Split(' '.ToArray()); 有一个错误,但你的代码有str.Split();。如果你没有首先发布不正确的代码,我们就不可能准确地告诉你什么代码是错误的。跨度>

标签: c# arrays winforms visual-studio-2012 visual-studio-2013


【解决方案1】:

解决方案在您的问题中。

在您给定的代码中,您试图在不分配参数的情况下拆分字符串。

string[] words = str.Split();

这不会将字符串拆分为多个部分。它只会在数组中创建一个元素。当您尝试从 word 数组的索引 1 访问第二个元素时。

tbData.Text = words[1].ToString();

这将给出索引 1 上没有元素的错误,数组中的元素计数只有 1,即索引 0。

所以,您可以从索引 0 获取字符串,也可以在 Split() 函数中指定参数。

string[] words = str.Split(' ');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    相关资源
    最近更新 更多