This blog is targeted at beginning / novice programmers for the Visual Basic (VB) language.

Tuesday, March 11, 2008

Processing a string into groups of 3

Today, I was browsing the vb.general.discussion newsgroup and came across a person who had wanted to take a textbox input and group the text into groups of 3 using a space to separate the groups. Example being:

Input: 1234567

Output: 1 234 567

Because I was unsure if they were dealing strictly with numbers I found the easiest method was to use the System.String namespace and create a function that would take the input and figure out the total number of groups within the input. It would then separate the groups into a group of 3 and while doing so insert a blank space between each group.

I thought those of you that are new to VB and, especially, new to the System.String namespace may want to see the power that is literally at your fingertips!

This example I had made within about 30 minutes; and was all made on the fly (I know, I know..I didn't plan it out; I was a bad programmer!...shhhh...don't tell anyone!). This is the 'complete' coding:

Setup: I had created a visual basic windows form. I inserted the following controls (left everything at the default settings/names):

2 x Buttons
2 x Labels
2 x Textboxes

Here's the coding I used:

Imports System.String

Public Class Form1
   
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
       
Application.Exit()
   
End Sub

   
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       
Dim strNewText As String

       
'Call custom function
        strNewText = Create3by3(TextBox1.Text.ToString)

       
'Assign results to textbox
        TextBox2.Text = strNewText
   
End Sub

   
Private Function Create3by3(ByVal strToProcess As String) As String
       
'Declare local variables
        Dim intLength, intNumGroups, intPosition As Short
       
Dim strTemp As String = ""
       
Dim intCount As Integer = 0

       
'Test if value is being passed, if not then notify end-user
        If strToProcess.Length = 0 Then
           
MessageBox.Show("Please enter a value to be processed before continuing.", _
                            "Missing value"
, MessageBoxButtons.OK, MessageBoxIcon.Stop)
           
TextBox1.Focus()
       
End If

       
'Set empty string; avoids warning message of variable not being assigned
        Create3by3 = ""
       
Try
           
'Check if value being passed is more than 3; if not then don't need
            'to go through complexity of processing the string
            If strToProcess.Length <= 3 Then
               
Create3by3 = strToProcess
               
Exit Function
           
End If

           
'Get total length we are working with
            intLength = strToProcess.Length

           
'Important to use the \ NOT the /; because we only want to deal with 
            'whole numbers, no decimals!
            intNumGroups = (intLength \ 3)

           
'This is used to determine the index position of the string we are
            'working with.
            intPosition = intLength - (intNumGroups * 3)

           
'This is a late declaration because it is dependant on how many
            'items we will want in our array which is how many groups we are
            'working with total (our division results + 1 for odd number of
            'the last group (first part of the string)
            Dim sSubStr(intNumGroups + 1) As String

           
'First we insert the odd number of characters; we start at index
            'position 0 and only move until we reach our first group
            sSubStr(intCount) = strToProcess.Substring(0, intPosition) + " "
           
'Don't forget to increase our array index since we filled our first
            'item in the array
            intCount += 1
           
'Now we just loop through the groups and add each one to the array
            For i = 0 To intNumGroups - 1
               
sSubStr(intCount) = strToProcess.Substring(intPosition, 3) + " "
               
'We increase the index position of the string by 3 since we are
                'working with a group of 3
                intPosition += 3
               
'We increase our array index to move to the next item in the array.
                intCount += 1
           
Next
           
'Now we simply just add the entire array into 1 large string
            'with our spaces we placed during our processing
            Create3by3 = String.Concat(sSubStr)
           
'Now we just remove the final spacing; because we don't need it and
            'we have the opportunity to do it now, instead of later.
            Create3by3 = Create3by3.TrimEnd(" ".ToCharArray)
       
Catch ex As Exception
           
'Catch any exceptions; biggest worry is the DivideByZero; but, we are
            'already testing for that at the beginning of this function
            MessageBox.Show("An exception was encountered." & vbCrLf & ex.Message)
       
End Try
       
'Return the results of our processed string!
        Return Create3by3
   
End Function
End Class

As you can see; this is actually not all the difficult of a task and most of the complex parts are already built into Visual Basic. How cool is that? All I needed to do was the split the string, keep track of how many groups there were; then just a matter of building a new string based on this information.

If you or anyone else has a question about this please do not hesitate to post a comment; I'd be happy to clarify it further!

Until next time....Happy Coding!!!

No comments: