仅将字符与字符串末尾的字符进行比较

时间:2012-10-21 00:10:46

标签: vb.net string

我正在Visual Basic 2010中编写一个程序,它列出了每个长度的单词在用户输入的字符串中出现的次数。虽然大部分程序都在运行,但我有一个问题:

当循环遍历字符串中的所有字符时,程序会检查是否存在下一个字符(这样程序不会尝试遍历不存在的字符)。例如,我使用条件:

If letter = Microsoft.VisualBasic.Right(input, 1) Then

letter是字符,input是字符串,Microsoft.VisualBasic.Right(input, 1)从字符串中提取最右边的字符。因此,如果letter是最右边的字符,程序将停止循环遍历字符串。

这就是问题所在。让我们说字符串是This sentence has five words。最右边的字符是s,但s也是第四和第六个字符。这意味着第一个和第二个s将像其他人一样打破循环。

我的问题是,是否有办法确保只有最后一个s或字符串中的最后一个字符可以打破循环。

2 个答案:

答案 0 :(得分:0)

VB.NET代码,用于计算每个长度的单词在用户输入的字符串中出现的次数:

Dim sentence As String = "This sentence has five words"
Dim words() As String = sentence.Split(" ")
Dim v = From word As String In words Group By L = word.Length Into Group Order By L

可能需要调整第2行以删除标点字符,修剪额外的空格等。

在上面的示例中,v(i)包含字长,v(i).Group.Count包含遇到此长度的字数。出于调试目的,您还有v(i).Group,这是一个String数组,包含属于该组的所有单词。

答案 1 :(得分:0)

您可以使用一些方法,一个是Neolisk显示的方法;这里有几个:

Dim breakChar As Char = "s"
Dim str As String = "This sentence has five words"

str = str.Replace(".", " ")
str = str.Replace(",", " ")
str = str.Replace(vbTab, " ")
' other chars to replace

Dim words() As String = str.ToLower.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)
For Each word In words
    If word.StartsWith(breakChar) Then Exit For
    Console.WriteLine("M1 Word: ""{0}""  Length: {1:N0}", word, word.Length)
Next

如果因任何原因需要循环使用字符,可以使用以下内容:

Dim breakChar As Char = "s"
Dim str As String = "This sentence has five words"

str = str.Replace(".", " ")
str = str.Replace(",", " ")
str = str.Replace(vbTab, " ")
' other chars to replace

'method 2
Dim word As New StringBuilder
Dim words As New List(Of String)

For Each c As Char In str.ToLower.Trim

    If c = " "c Then
        If word.Length > 0 'support multiple white-spaces (double-space etc.)
            Console.WriteLine("M2 Word: ""{0}""  Length: {1:N0}", word.ToString, word.ToString.Length)
            words.Add(word.ToString)
            word.Clear()
        End If
    Else
        If word.Length = 0 And c = breakChar Then Exit For
        word.Append(c)
    End If
Next

If word.Length > 0 Then
    words.Add(word.ToString)
    Console.WriteLine("M2 Word: ""{0}""  Length: {1:N0}", word.ToString, word.ToString.Length)
End If

我专门写这些是为了打破你所要求的第一个字母,根据需要进行调整。