Thursday, February 2, 2012

String arrays and For Each Loops

Hack The Gibson
This particular post comes by way of special request.  The idea behind this article is that we want to create a string array, then populate said string array with the name of sports teams (either from a file/xml or other method…)
Once we have this accomplished, we need to perform a count against the array and see how many times a particular team has won.  Think this will take a lot of code?  Nay, in less than 30 lines we can have the entire requirement complete:
   1: Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
   2:         Dim arrString() As String = {"Braves", "Dodgers", "Braves", "Cubs"}
   3:         Dim countBraves As Integer = 0
   4:         Dim countDodgers As Integer = 0
   5:         Dim countCubs As Integer = 0
   6:  
   7:         For Each team In arrString
   8:             If team = "Braves" Then
   9:                 countBraves += 1
  10:             ElseIf team = "Dodgers" Then
  11:                 countDodgers += 1
  12:             ElseIf team = "Cubs" Then
  13:                 countCubs += 1
  14:             End If
  15:  
  16:         Next
  17:  
  18:         If countBraves > countDodgers Then
  19:             If countBraves > countCubs Then
  20:                 lblWinner.Text = String.Format("The BRAVES are the winner with {0:n0} wins.", countBraves)
  21:             Else
  22:                 lblWinner.Text = String.Format("The CUBS are the winner with {0:n0} wins.", countCubs)
  23:             End If
  24:         ElseIf countDodgers > countCubs Then
  25:             lblWinner.Text = String.Format("The DODGERS are the winner with {0:n0} wins.", countDodgers)
  26:         Else
  27:             lblWinner.Text = String.Format("The CUBS are the winner with {0:n0} wins.", countCubs)
  28:         End If
  29:     End Sub

So obviously, we are starting on a PAGE_LOAD trigger.
From there I Dimension a String array.  I instantiate the array with a simple list of teams.  The curly brackets indicate a list.  Notice I have comma delimited the list, this is how arrays are built virtually.  We could have easily read lines from a file, xml, or any other data source OR we could have instantiated it using the keyword NOTHING, which would tell the processor we would like to populate the array later or “not at this time”…
Incidently – If you insert a breakpoint at line 3 and look at your local variables window, you can see the count property for the arrString which will tell you how many items exist in the array.

Now we need to create some counters so that we can keep score.  I instantiated these counter/integers to 0 because we do not know how many times they have won yet.

Now comes the interesting part.  The FOR EACH Loop.  One of the interesting things of a FOR EACH Loop is that all the hard work is completed for you.  In a normal array you have to take account that the first place value in an array is 0.  Well in a FOR EACH Loop, it is understood that you do not care about placement, only the values.  In the case of the code above, the variable team is a local scope representation of a specific value in the array (local scope because the variable looses scope outside the FOR EACH Loop). 
So take for instance if we were to run the code above, the first pass through the FOR EACH Loop the value of team would be “Braves”.  Do we care that we are at the first placement value? Nay, we only care what the value at ANY placement is (In this case we are more concerned with how many times a value appears).
So then we enter our IF/THEN statements where we increment our counter by 1 based on value.  Notice that we are using “short code” to increment the counter (we could have also wrote the code as: counterBraves = counterBraves + 1).

Once we are done counting we move to our IF/ElseIF/Then comparison to print our winner.  We have employed the use of String.Format here.  Don’t underestimate the power of this little gem of a method.  Again, here we are using another sort of string array, while formatting it at the same time!  Suppose I wanted to write the statement:
The Braves won 2 times, the Dodgers 1 time, and the Cubs 1 time.
We would use the following code to implement the sentence above:


   1: String.Format("The Braves won {0}, the Dodgers {1} time, and the Cubs {2} time.", countBraves, countDodgers, countCubs)

The curly brackets with the number inside represents the placement value in the array of the value that you want to show up.  Of course our array is comma delimited as represented in the code above.  This all happens WHILE the string.format method converts the value to string.  We couldn’t build a string with an integer value in the middle of it (the compiler kind of complains to us about that sort of thing).
Now why do you suppose that they would call the method String.Format?  It’s because on top of all this other magic that Microsoft allows this method to perform for us, it can also format objects as it converts it to strings WHILE placing it within our string from the array.  Take the following example:



   1: String.Format("The Braves have won {0:n0} times.", countBraves)

Notice that in the method above I have asked it to place value 0 (countBraves) inside the string, convert it to a string AND the n0 (the letter n and a zero) represents that I want it to keep numeric formating, I.E. 1,234.  It will place the commas in the correct place.  If we changed it to {0:n2} it would then output 1,234.00 (as the number 2 represents the number of decimal places we want). 
n represents numbers, however Microsoft has given us some other parameters to use to display different types of type values while converting them to a string.  For instance, p represents percent and would look like {0: p}.  A quick google search of String.Format and you can find numerous parameters to use.
If that wasn’t enough you can also make custom parameters like so {0:#,###.##) which means I would expect a number, a comma, three numbers, a decimal, and two final numbers.

String.Format is probably one of the most used functions inside of .Net.  If you aren’t using it, you are missing out on an extremely powerful feature (and you need to get your act together).

At any rate -

Happy .Netting…Saleh
HACK THE GIBSON

No comments:

Post a Comment