-3
我試圖分裂在C#中的字符串,我用這個代碼:的C#Windows應用程序數組和字符串分割
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中
_「但我有一個錯誤」 _始終在你的問題的錯誤... – 2014-09-01 01:25:16
拆分方法將返回的String []。什麼是你的問題。行str .Split(''.ToArray());也錯了。 – Seminda 2014-09-01 01:30:39
您收到的異常似乎表明您的'str'沒有任何價值。你有沒有在調試器中驗證過'str'確實有價值? – Claies 2014-09-01 01:43:26