【发布时间】: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