Count the number of occurrences of each character in a string, ignoring CRs
I'm scanning through all characters in a textbox. Then the progr开发者_C百科am counts how many of each character is in the textbox. Here's the code which adds all characters to a list:
For each c as char in TxtBox
list.add(c)
Next
Everything's working fine, except this will also add returns to the list, which I don't want. I thought I could write like this:
If c <> chr(10) Then
list.add(c)
End If
...but it's not working. Any ideas?
You would also need to exclude chr(13). 10 = new line, 13 = carriage return.
For each c as char in TxtBox
if c <> chr(10) and c <> chr(13) then
list.add(c)
end if
Give that a shot.
In Windows, both LF = LineFeed = Chr(10) and CR = Carriage Return = Chr(13) are inserted as return character.
This comes from (old) dot-matrix printers.
LineFeed = Move one line down
Carriage Return = Move to the begin of the current line
They are both included in the Environment.NewLine
property.
So your code should be something like:
If Environment.NewLine.IndexOf(c) < 0 Then
list.Add(c)
End If
This way your are sure your code also works on OS'es that use different characters for newline.
Well, there are already lots of answers, but the way I would have done it is as follows:
For Each c As Char In TextBox1.Text.Replace(vbCrLf, "")
List.Add(c)
Next
I don't know what your "List" variable is, but if it's of a List type, or of type ListBox.ObjectCollection, or of many other types, you could probably replace this loop with:
List.AddRange(TextBox1.Text.Replace(vbCrLf, "").ToCharArray())
...just for the fun of it!
Use the http://msdn.microsoft.com/en-us/library/system.char.iswhitespace.aspx
Char.IsWhiteSpace
精彩评论