获得IndexOf的特征

时间:2017-01-07 20:45:35

标签: vb.net

对于一个分配,我的老师要求我们从文件中读取以查找我们姓名的字符,并将它们放在表单顶部的标签上。

这是我的代码:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    searchFile = File.OpenText("AcademicEthicsandIntegrityStatement.txt")


    Dim s As String = searchFile.ReadToEnd
    Dim b As String = s.IndexOf("b"c)
    Dim r As Integer = s.IndexOf("r"c)
    Dim i As Integer = s.IndexOf("i"c)
    Dim a As Integer = s.IndexOf("a"c)
    Dim n As Integer = s.IndexOf("n"c)
    Dim ec As Integer = s.IndexOf("e"c)

    Dim bRead = GetChar(s, b)
    Dim rRead = GetChar(s, r)
    Dim iRead = GetChar(s, i)
    Dim aRead = GetChar(s, a)
    Dim nRead = GetChar(s, n)
    Dim ecRead = GetChar(s, ec)
    lblName.Text = bRead + rRead + iRead + aRead + nRead + nRead + ecRead
End Sub

正在阅读我的lbl的文字是“gmcaad”而不是“brianne”

我确定我在这里遗漏了一些东西,或者有一种更简单的方法可以做到这一点。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

IndexOf返回从零开始的索引 GetChar接受基于一个索引。

为了保持一致性,

  • 如果您想使用IndexOf,请使用直接索引而不是GetChar

    Dim bRead = s(b)
    Dim rRead = s(r)
    
  • 如果您想使用GetChar,请使用InStr代替IndexOf,同时返回基于1的值。

答案 1 :(得分:0)

简答题:区分大小写:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    With File.ReadAllText("AcademicEthicsandIntegrityStatement.txt")
        For Each C As Char In "Brianne".ToCharArray
            ' Note this is case-sensitive because it uses a binary comparison
            Dim Index As Integer = .IndexOf(C)
            If Index >= 0 Then lblName.Text &= .Substring(Index, 1)
        Next
    End With
End Sub

......并且不区分大小写:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    With File.ReadAllText("AcademicEthicsandIntegrityStatement.txt")
        For Each C As Char In "Brianne".ToCharArray
            ' Note this is not case-sensitive
            Dim Index As Integer = .IndexOf(C.ToString, StringComparison.InvariantCultureIgnoreCase)
            If Index >= 0 Then lblName.Text &= .Substring(Index, 1)
        Next
    End With
End Sub