2013-11-15 100 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里面是什么?

相关问题