Recipe 5.12. Tallying Characters


You want to tally, or count the occurrences of, each character value in a string.


Sample code folder: Chapter 05\TallyCharacters

Convert the string to a byte array, and then tally the 256 possible byte values into an array of integer counts.


In the case presented, the string is assumed to be all ASCII, which means conversion using UTF8 encoding is appropriate, and the tally array only needs to be dimensioned to hold 256 counting bins:

 Dim quote As String = "The important thing is not to " & _    "stop questioning. --Albert Einstein" Dim counter As Integer Dim tally(255) As Integer 

Convert the string to a byte array, and then loop through each byte of the array to increment the count for each byte value:

 Dim bytes() As Byte = _    System.Text.Encoding.UTF8.GetBytes(quote) For counter = 0 To bytes.Length - 1    tally(bytes(counter)) += 1 Next counter 

The rest of the example prepares the tally for display. For efficiency, the code presents only characters with nonzero counts:

 Dim result As New System.Text.StringBuilder(quote) For counter = 0 To 255    If (tally(counter) > 0) Then       result.AppendLine( )       result.Append(Chr(counter))       result.Append(Space(3))       result.Append(tally(counter).ToString( ))    End If Next counter MsgBox(result.ToString( )) 

Figure 5-10 shows the results.

Figure 5-10. A quick tally of the characters in a string

If you want to tally Unicode characters, you need to either dimension a much larger tally array or use a lookup system that constantly adds and counts characters as it finds them.

See Also

Recipe 5.11 provides additional details on encoded conversions.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: