hello, i'm new to the forum, and a bit new to vb as well. i'm in 11th grade in i'm taking a programming class [and absolutely loving it]. the assignment he just gave us was just to create something useful, within certain parameters of course. i ended up choosing a text document browser, something in between MS word and notepad. i seem to have hit a little snag though; i am trying to do a WordCount function. Here is my code:
right now, what this code does basically is finds every space after any character that is not a space, and "x += 1" it to a counter. after i checked for spaces, i realised my code didn't account for words at the end of a line unless i added a space after it. also, it counts a space at the beginning of a line as a word. so i did some debugging. i found that, if you rollover string "s" while debugging i couldnt find the newline character anywhere. my forloops weren't either, obviously. i even tried changing the newline character to something else to get it to recognize it:
i used "¾" becasue i didn't want it being a common character that could cause a flaw in the counting. but either way, it didn't find any newline character anywhere and nothing was replaced.
please help! i'm sure there's something incredibly simple i'm missing. thank you!
VB.NET:
Private Sub WordCount()
Dim x As Integer
Dim s As String = RichTextBox1.Text
Dim spaceCounted As Boolean = False
For i As Integer = 0 To CInt(RichTextBox1.Text.Length) - 1
If spaceCounted = False Then
'bug fixed: now only spaces after other characters are counted, not multiple spaces in a row
If s(i) = ControlChars.NewLine Then
x += 1
spaceCounted = True
End If
If s(i) = " " Then
x += 1
spaceCounted = True
End If
ElseIf spaceCounted = True Then
'checks to see if a new word started, the the space after the word triggers "+=1" on word count
If Not (s(i) = " " Or s(i) = ControlChars.NewLine) Then
spaceCounted = False
End If
End If
Next
tssWordCount.Text = "WordCount: " & x.ToString
End Sub
right now, what this code does basically is finds every space after any character that is not a space, and "x += 1" it to a counter. after i checked for spaces, i realised my code didn't account for words at the end of a line unless i added a space after it. also, it counts a space at the beginning of a line as a word. so i did some debugging. i found that, if you rollover string "s" while debugging i couldnt find the newline character anywhere. my forloops weren't either, obviously. i even tried changing the newline character to something else to get it to recognize it:
VB.NET:
s = RichTextBox1.Text
s.Replace(ControlChars.NewLine, "¾")
i used "¾" becasue i didn't want it being a common character that could cause a flaw in the counting. but either way, it didn't find any newline character anywhere and nothing was replaced.
please help! i'm sure there's something incredibly simple i'm missing. thank you!
Last edited: