在VB.NET中利用Split和Replace函数计算字数

Split函数使你能够将长字符串分离为单独的字;但是如果在字与字之间不止一个空格,Split就会返回一个错误的结果。为了防止这种情况发生,你可以在使用Split之前用Replace函数来替换多个空格的出现。列表A给出了一个例子。

列表A

Private Sub CountWords()Dim strText As String = "It's a wonderful world"Dim iCount As IntegerDo While (strText.IndexOf(Space(2)) >= 0)strText = strText.Replace(Space(2), Space(1))LoopiCount = Split(strText, Space(1)).LengthMsgBox(iCount.ToString())End Sub

在这个例子中,我创建了字符串strText,再将它设置成有多个字符的长字符串。然后,我利用Replace函数来把出现的多个空格替换成一个空格。这样做是为了把字符串strText准备就绪,让你能够使用Split函数并提供正确的结果。

接着,我将strText输入Split函数,并且得到了包括在字符串strText中的字数。注意:如果你跳过或注释用来移除多余空格的循环,结果是7个字。使用移除所有多余空格的循环后,结果才是正确的,4个字。

Private Sub CountWords()Dim strText As String = "It's a wonderful world" Dim iCount As IntegerDo While (strText.IndexOf(Space(2)) >= 0) strText = strText.Replace(Space(2), Space(1)) LoopiCount = Split(strText, Space(1)).Length MsgBox(iCount.ToString())End Sub