在该行中找到单词,特定字母的开头和单词,相同字母的结尾

时间:2019-05-24 15:35:30

标签: arrays string vb.net

给定一个带有单词的字符串,由问题分隔,我需要找到哪个单词之前出现:哪个单词以字母“ k”开头或以“ k”结尾

我尝试使用Mid和Len运算符来实现,但是现在我需要使用Substring和Length

Sub uncorrect(ByVal s As String, ByRef res As String)
    Dim i As Integer
    Dim t, w As String
    s = s + " "
    w = ""
    For i = 1 To Len(s)
        t = Mid(s, i, 1)
        If t = " " Then
            If (Mid(w, 1, 1) = "k") Then
                res = "Word, begin with k"
                Exit Sub
            Else
                If (Mid(w, Len(w), 1) = "l") Then
                    res = "Word, end with k"
                    Exit Sub
                End If
            End If
            w = ""
        Else
            w = w + t
        End If
    Next
End Sub

Sub trying(ByVal s As String, ByRef res As String)
    Dim i As Integer
    Dim mass = s.Split(" ")
    For i = 0 To mass.Length - 1
        If mass(i).Substring(1, 1) = "k" Then
            res = "Word, begin with k"
            Exit For
        Else
            If mass(i).Substring(mass(i).Length - 1, 1) = "k" Then
                res = "Word, end with k"
                Exit For
            End If
        End If
    Next
End Sub

实际输出非常不稳定:或者结果文本框为空,或者错误

2 个答案:

答案 0 :(得分:0)

如果只需要一个字符,则不需要使用子字符串。您可以通过使用默认属性指定索引来获取字符。

Sub trying(ByVal s As String, ByRef res As String)
    Dim i As Integer
    Dim mass = s.Split(" "c)
    For i = 0 To mass.Length - 1
        If mass(i)(0) = "k"c Then
            res = "Word, begin with k"
            Exit For
        Else
            If mass(i)(mass(i).Length - 1) = "k"c Then
                res = "Word, end with k"
                Exit For
            End If
        End If
    Next
End Sub

答案 1 :(得分:0)

我使用Linq创建了一个函数,该函数返回具有符合条件的单词的List(Of String)。我修剪了所有标点符号,并使用String.StartsWith和String.EndsWith进行了测试。为了进行测试,我将结果打印到立即窗口中。

Private Function GetWords(input As String) As List(Of String)
    Dim words = input.Split(" "c)
    Dim Kwords = (From S In words
                  Let TrimmedS = S.Trim(New Char() {","c, "."c}) 'and whatever other puncuation you need to trim
                  Where TrimmedS.StartsWith("K", StringComparison.OrdinalIgnoreCase) OrElse TrimmedS.EndsWith("K", StringComparison.OrdinalIgnoreCase)
                  Select TrimmedS).ToList
    Return Kwords
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim KWords = GetWords("The quick fox")
    Debug.Print("The quick fox")
    For Each w In KWords
        Debug.Print(w)
    Next
    Dim KWords1 = GetWords("Kick, scream, and knock out.")
    Debug.Print("Kick, scream, and knock out.")
    For Each w In KWords1
        Debug.Print(w)
    Next
End Sub

结果:

The quick fox  
quick  
Kick, scream, and knock out. 
Kick 
knock