1

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

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

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

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

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

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

4

2 回答 2

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,它包含属于该组的所有单词。

于 2012-10-21T01:20:19.663 回答
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

我写这些是为了按照你的要求在一个单词的第一个字母上打断,根据需要进行调整。

于 2012-10-21T09:38:38.917 回答