2014-09-01 18 views
-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中

+2

_「但我有一個錯誤」 _始終在你的問題的錯誤... – 2014-09-01 01:25:16

+0

拆分方法將返回的String []。什麼是你的問題。行str .Split(''.ToArray());也錯了。 – Seminda 2014-09-01 01:30:39

+0

您收到的異常似乎表明您的'str'沒有任何價值。你有沒有在調試器中驗證過'str'確實有價值? – Claies 2014-09-01 01:43:26

回答

0

解決方案是在你的問題。

在你給定的代碼中,你正試圖分割一個字符串而不分配一個參數。

string[] words = str.Split(); 

這不會將字符串拆分爲多個部分。它只會在數組中創建一個元素。當您嘗試訪問來自word數組的索引1中的第2個元素時。

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

這會得到有關於指數1沒有元素元素的數量陣列中的計數誤差僅爲1於指數0

所以,要麼你可以從指數得到字符串0或指定Split()函數中的參數。

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