2013-11-15 47 views
0

我知道這應該很容易..但是,每次運行此代碼時,它都會告訴我第一行的第一個字符,那麼它將返回「」以表示所有後續字符.....獲取文本框中每行的第一個字符vb.net

Dim firstChar As Char 

' Split on New Line 
For Each strLine As String In TextBox1.Text.Split(vbNewLine) 

    firstChar = strLine.First() 

    If firstChar = "[" Then 
     MessageBox.Show("I found it!") 
    End If 
Next 
+0

我們可以看到你輸入的數據? – MichaelEvanchik

+0

他們是「」的原因是因爲你需要檢查http://msdn.microsoft.com/en-us/library/system.stringsplitoptions(v=vs.110).aspx,但也使用不同的方法,如其他答案指出。 – JDwyer

回答

3

通過新行字符使用TextBoxLines值,而不是分裂的,就像這樣:

Dim lines() As String 
lines = TextBox1.Lines 

現在,你可以通過字符串數組循環,讓每個字符串的第一個字符,像這樣:

For Each line As String In lines 
    ' Protect against strings that do not have a first letter to check 
    If line.Length >= 1 Then 
     Dim firstLetter As Char 
     firstLetter = line.Substring(0, 1) 
    End If 
Next 

然後你就可以把邏輯來檢查的第一個字母是一定值,就像這樣:

If firstLetter = "[" Then 
    MessageBox.Show("I found it!") 
End If 

注:以上我概述了隔離措施,但很明顯,你可以結合一些這些東西一起爲更簡潔的解決方案,如:

For Each line As String In TextBox1.Lines 
    ' Protect against strings that do not have a first letter to check 
    If line.Length >= 1 Then 
     Dim firstLetter As Char = line.Substring(0, 1) 

     If firstLetter = "[" Then 
      MessageBox.Show("I found it!") 
     End If 
    End If 
Next 
+0

當我的字符到達末尾時,我得到了一個越​​界異常。 –

+0

@PeterBlack - 答案更新,以防止檢查空字符串中的第一個字母。 –

0
firstChar = strLine.Substring(0,1) 

更是用什麼IM編碼,從來沒有見過一前,不是說其無效,但可能是一個問題?也vbNewLine雖然是正確的,我會分裂在char(10)或char(13),因爲有時它不是兩個。另外,在調試器中的strLine裏面是什麼?

相關問題