Manipulating Data

   

Now that you can make all kinds of variables with different data types, it will be helpful for you to understand how to manipulate your data as well.

What happens when you need to add two number type variables together? Or what if you need to find out whether a specific word appears in a string? The following sections look at a bunch of these types of functions.

Number Manipulation

Manipulating numbers is nothing more than doing math. It's either addition, subtraction, multiplication, or division. Let's look at the operations and their operators.

Let's declare some variables and perform some mathematical operations and see what we get. We'll use some of our cool short cuts for declaring and initializing variables.

Visual Basic .NET basic_math_vb.aspx
'Cool variable declaration  Dim var1,var2,var3,var4,vartotal As Integer  var1 = 3  var2 = 4  var3 = 5  var4 = 6  varTotal = 0  'Addition  varTotal = var1 + var2  OurLabel.Text+= "Addition: " & varTotal & "<br>"  'Subtraction  varTotal = var3 - var2  OurLabel.Text+= "Subtraction: " & varTotal & "<br>"  'Multiplication  varTotal = var1 * var2  OurLabel.Text+= "Multiplication: " & varTotal & "<br>"  'Division  varTotal = var4 / var1  OurLabel.Text+= "Division: " & varTotal & "<br>" 
C# basic_math_cs.aspx
/* Very cool C# declaration and initialization  code that lets us perform this on one line */  int var1=3,var2=4,var3=5,var4=6,varTotal=0;  //Addition  varTotal = var1 + var2;  OurLabel.Text += "Addition: " + varTotal + "<br>";  //Subtraction  varTotal = var3 - var2;  OurLabel.Text += "Subtraction: " + varTotal + "<br>";  //Multiplication  varTotal = var1 * var2;  OurLabel.Text += "Multiplication: " + varTotal + "<br>";  //Division  varTotal = var4 / var1;  OurLabel.Text += "Division: " + varTotal + "<br>"; 

The results are delivered as expected in Figure 3.1.

Figure 3.1. Computers excel at doing math and have no problem handling very complex mathematical operations.
graphics/03fig01.gif

Tip

I have added comments to these two previous code blocks to demonstrate how you can add comments to both Visual Basic .NET and C#. The single quote (') is the character in Visual Basic .NET that signifies a line is a comment, and anything on that single line is ignored. The comment indicator for a single line in C# is two forward slashes(//). C# also has a way for you to insert a multi-line comment, which is displayed above the variable declaration in the C# example. Anything between a forward slash star combination for the opening of the comment and a star-forward slash combination (/* put your comment in here */) for the close of the comment will be ignored. Note that comments can be on a line with executed code. Anything after the comment delimiter will be ignored.


As you can see, math operates just as you would expect it to. Addition, subtraction, multiplication, and division are basic functions of the numeric operators. Both Visual Basic .NET and C# offer some shortcuts for some common situations in math operation. For instance, you might want the value of a variable to be set to the value of adding another variable to itself. This typically would look as follows in both languages (with the exception of a semicolon at the end of the line in C#):

 var1 = var1 + var2 

We now have a shortcut option that produces the same results:

 var1 += var2 

The += operator sets var1 to the sum of var1 + var2, but saves the trouble of writing out var1 twice. There are shortcuts for each of the four basic math functions, as well as other timesaver operators that you'll discover as you progress through the book.

"Thanks for the math lesson, Peter, but I learned all that in 3rd grade." Sorry, but I think it's important to cover some of the most basic concepts on which we will build more complex functions later in the book. Otherwise, I fear that there will be weak spots in your understanding that will make everything else more difficult to pick up. Understanding these basic functions and how they are properly executed will prove to be an invaluable asset as we dig into the deeper stuff later.

String Manipulation

Manipulating strings of characters is a bit more challenging than some of the math concepts. You'll see some basic functions in the following sections such as joining two strings together but you'll also explore lopping off certain portions of a string, or checking to see whether a certain word appears in a string.

There are a ton of different functions available to mess around with strings, and you'll see that they come in very handy in many situations.

Concatenation

Concatenation? No, it isn't a country full of criminal felines! It's another one of those REALLY BIG programmer words. The definition of concatenate is "to link things together." So concatenating is simply sticking strings together. Take a look:

Visual Basic .NET string_concate_vb.aspx
dim var1,var2,var3 as string  var1 = "ASP.NET is "  var2 = "very cool!"  var3 = var1 + var2 '<<< Yippee!! Concatenation  OurLabel.Text = var3 
C# string_concate_cs.aspx
string var1,var2,var3;  var1 = "ASP.NET is ";  var2 = "very cool!";  var3 = var1 + var2; // <<< WAHOO!! Concatenation  OurLabel.Text = var3; 

And you get a concatenated string as shown in Figure 3.2.

Figure 3.2. Concatenating strings is the process of linking strings together.
graphics/03fig02.gif

Note

As you saw when we manipulated numbers, the same operators are used in both languages to perform a mathematical function. There is a difference in the operator when it comes to string concatenation. In Visual Basic .NET, the ampersand (&) or the plus (+) sign can be used as the operator to concatenate strings, but only the plus (+) sign is used to perform this function in C#. The ampersand is basically a holdover from VBScript, but for the sake of consistency I recommend you use the plus sign. Using the ampersand allows you to concatenate a string and a number without creating an error, but this is the beginning of a slippery slope of bad coding habits that is easy to fall into. It's better to use the plus sign and use the number's ToString() method if you need to concatenate a string and a number.


As you continue to investigate all the fabulous things you can do with strings, I would again encourage you to go to the .NET Framework class browser I mentioned in Chapter 2 and look at all the built-in properties and methods for the System.String class, which is what we are dealing with here. We are going to go over a bunch of them, but there are like a wheelbarrow full Too many to cover thoroughly here.

Just a note if you come from a traditional ASP programming background: This is gonna be a bit of a change for you from what you are accustomed to when manipulating strings with ASP functions. Most of the function is still there, with a few exceptions and consolidations, but they aren't functions anymore they are methods.

Length

Let's start by looking at the Length property. It's the only property we are going to cover here. The rest are System.String methods. The Length property returns (without any surprise) the length or number of characters in the string.

Visual Basic .NET string_length_vb.aspx
dim var1 as string  var1 = "ASP.NET is very cool!"  OurLabel.Text = var1.length + " characters long" 
C# string_length_cs.aspx
string var1;  var1 = "ASP.NET is very cool!";  OurLabel.Text = var1.Length + " characters long"; 

And you can see the results in Figure 3.3.

Figure 3.3. If you need to find out how many characters (including spaces) are in a string, you ask for the length property.
graphics/03fig03.gif

Warning

Remember when calling properties and methods in C# that you must match the case of the Frameworks' property. For instance in the System.String class the Length property has a capital L . If you use a lowercase l , you will throw an error that says that a string doesn't have a length property. In C#'s eyes it doesn't have l ength property, it has L ength property.


Substring()

A very useful System.String method is called Substring(). You may be familiar with a similar method in JavaScript with the same name. When we were still programming in ASP using VBScript as our script language, there were three different functions that this single Substring() function replaces: Left, Right and Mid. These functions no longer exist, and just about anything that you could perform with them can be achieved with this single method of the System.String class.

To demonstrate the Substring() method, I'll use the opening line from the book, "It was a dark and stormy night in Chicago." We are going to use Substring() to hack, pick, and prod this string apart.

Visual Basic .NET string_substring_vb.aspx
dim OurString,MySubStr as String  OurString = "It was a dark and stormy night in Chicago"  'Show first 11 characters  MySubStr = OurString.Substring(0,11)  OurLabel.Text += "First 11 Characters: " + MySubStr + "<br>"  'Show last 4 characters  MySubStr = OurString.Substring(37)  OurLabel.Text += "Last 4 Characters: " + MySubStr + "<br>"  'Show 3 character from the middle  MySubStr = OurString.Substring(10,3)  OurLabel.Text += "3 Middle Characters: " + MySubStr 
C# string_substring_cs.aspx
String OurString,MySubStr;  OurString = "It was a dark and stormy night in Chicago";  //Show first 11 characters;  MySubStr = OurString.Substring(0,11);  OurLabel.Text += "First 11 Characters: " + MySubStr + "<br>";  //Show last 4 characters;  MySubStr = OurString.Substring(37);  OurLabel.Text += "Last 4 Characters: " + MySubStr + "<br>";  //Show 3 character from the middle;  MySubStr = OurString.Substring(10,3);  OurLabel.Text += "3 Middle Characters: " + MySubStr; 

Now look at the results in Figure 3.4.

Figure 3.4. You can cut out portions of a string by using the Substring() method.
graphics/03fig04.gif

Now let's investigate. Let's start with the first call to the method, where we extract the first 11 characters of the string.

 OurString.Substring(0,11) 

The first parameter of 0 tells the Substring() method where to start the chopping. The second parameter of 11 tells the method how many character to chop. So, basically, we can say that the Substring() method was told: "Start chopping at character 0 and give me 11 characters from there.

The third example that pulls the characters out of the middle of the string is not really different. It simply starts at character 10 and proceeds to return 3 characters.

 OurString.Substring(10,3) 

Now you can look at a real-world version of an overloaded method in the second example of the Substring() method:

 OurString.Substring(37) 

You can see that only one parameter of 37 is being passed into the Substring() method . This Substring() method knows that if you provide only one parameter, you want everything from the starting provided parameter to the end of the string. Basically, the previous example told the Substring(): "Give me everything from character 37 to the end of the string."

Note

Just an aside here. If you remember back in Chapter 2, overloaded methods enable you to send multiple "variable signatures" to a method, and then the .NET Framework figures out which version of the method you are referencing. The Substring() method is a perfect example of an overloaded method, and the previous examples illustrate passing different "variable signatures" to the overloaded method.


Now I am even going to touch on some other methods briefly to show how you can use multiple methods and properties to achieve the results you want.

Let's imagine we are trying to locate and extract a certain word from a string. For instance, maybe you're trying to see whether the word "stormy" appears in the string. You don't know where it is exactly, but you need to find and extract it. Here's a tricky way to pull it out using some combinations of methods and properties.

Visual Basic .NET string_substring_findword_vb.aspx
dim OurString,OurWord,OurFoundWord as String  OurString = "It was a dark and stormy night in Chicago"  OurWord = "stormy"  OurFoundWord = OurString.Substring(OurString.IndexOf(OurWord),OurWord.Length)  OurLabel.Text = OurFoundWord 
C# string_substring_findword_cs.aspx
String OurString,OurWord,OurFoundWord;  OurString = "It was a dark and stormy night in Chicago";  OurWord = "stormy";  OurFoundWord = OurString.Substring(OurString.IndexOf(OurWord),OurWord.Length);  OurLabel.Text = OurFoundWord; 

This block of code writes the word "stormy" to the page. Let's see how. If you investigate the Substring() method call, you can see that two parameters are being passed.

 1: OurString.IndexOf(OurWord)  2: OurWord.Length 

The first parameter uses another method of the System.String class called IndexOf(). You pass this method a parameter of OurWord that contains the word "stormy." Basically, the IndexOf() method returns a number value of the start position of the first occurrence of the parameter passed to it. In this case it passed the value of 18, which is the first character of the word "stormy" in OurString.

The second parameter is next. It contains the length of OurWord, "stormy", which is 6, using the Length parameter of the String object. Basically we are passing

 OurString.Substring(18,6) 

You can begin to see how you might use this to pass parameters that depend on a user's input or a dynamically determined variable to manipulate strings using the Substring() method.

ToUpper(), ToLower()

There may be times when you are messing around with strings and you need to adjust the case of a string's characters. System.String has provided two ways: the ToUpper() and ToLower() methods. The names are pretty self-explanatory, so look at some examples of this action:

Visual Basic .NET string_casechange_vb.aspx
dim OurString as String  OurString = "It WAs a DaRk aND sToRMy Night in ChicAgo"  OurLabel.Text += "Original String:" + OurString + "<br><br>"  OurLabel.Text += "ToUpper Example:" + OurString.ToUpper + "<br><br>"  OurLabel.Text += "ToUpper Example:" + OurString.ToLower 
C# string_casechange_cs.aspx
String OurString;  OurString = "It WAs a DaRk aND sToRMy Night in ChicAgo";  OurLabel.Text += "Original String:" + OurString + "<br><br>";  OurLabel.Text += "ToUpper Example:" + OurString.ToUpper() + "<br><br>";  OurLabel.Text += "ToUpper Example:" + OurString.ToLower(); 

As you can see by the results in Figure 3.5, the ToUpper() method capitalizes all the characters of the string and the ToLower() method makes all the characters lowercase.

Figure 3.5. Use the ToUpper() and ToLower() methods to manipulate a string to uppercase or lowercase.
graphics/03fig05.gif

I purposely left out the parentheses of the ToUpper() and ToLower() method calls of the Visual Basic .NET example to illustrate another situation where Visual Basic .NET will allow you to "get away" with something. Again, I recommend you avoid these types of habits because they will create issues for you if you need to move across languages and program in C#.

Replace()

Replace() is a handy-dandy method for string manipulation if you need to locate occurrences of a particular word or phrase and replace it with something else.

Visual Basic .NET string_replace_vb.aspx
dim OurString as String  OurString = "It was a dark and stormy night in Chicago"  OurLabel.Text += "Original String: " + OurString + "<br><br>"  OurLabel.Text += "Replaced String: " + OurString.Replace("dark and stormy night","bright  graphics/ccc.gifand shiny day") 
C# string_replace_cs.aspx
String OurString;  OurString = OurString = "It was a dark and stormy night in Chicago";  OurLabel.Text += "Original String: " + OurString + "<br><br>";  OurLabel.Text += "Replaced String: " + OurString.Replace("dark and stormy night","bright  graphics/ccc.gifand shiny day"); 

You can see the results in Figure 3.6.

Figure 3.6. The Replace() method provides a way to find and replace occurrences of a string inside another string.
graphics/03fig06.gif

You will find many uses for the Replace() method, as it provides you with ways to achieve desired results very easily. For instance, I had a client who didn't like that the results of a Boolean variable were displaying True and False. I simply used the Replace() method to change this to Yes and No as the client wanted.

The Replace() method is case sensitive. If you are attempting to replace a word such a "Dark" and it appears in lowercase in the string as "dark," the Replace() method will not see this as a match. This is not language-specific; it is a characteristic of the method and not any language.

Date Manipulation

Dates are pretty standard and are used quite often when building web applications. There are many times when you will need dates and times formatted in a certain way, or you may need to display only a certain portion of a date or time.

The .NET Framework provides many functions and properties to deal with dates and times. The following code block demonstrates a whole bunch of the available properties and methods, but remember this isn't an exhaustive list, just a sampler.

Visual Basic .NET datetime_vb.aspx
dim MyDate as DateTime = DateTime.Now  OurLabel.Text = "MyDate: " + MyDate + "<BR><BR>"  OurLabel.Text += "<B><U>Date Properties:</U></B><BR>"  OurLabel.Text += "MyDate.Hour: " + MyDate.Hour.tostring + "<BR>"  OurLabel.Text += "MyDate.Day: " + MyDate.Day.tostring + "<BR>"  OurLabel.Text += "MyDate.DayOfWeek: " + MyDate.DayOfWeek.tostring + "<BR>"  OurLabel.Text += "MyDate.DayOfYear: " + MyDate.DayOfYear.tostring + "<BR>"  OurLabel.Text += "MyDate.Month: " + MyDate.Month.tostring + "<BR>"  OurLabel.Text += "MyDate.Year: " + MyDate.Year.tostring + "<BR><BR>"  OurLabel.Text += "<B><U>Date Methods:</U></B><BR>"  OurLabel.Text += "MyDate.ToShortTimeString: " + MyDate.ToShortTimeString + "<BR>"  OurLabel.Text += "MyDate.ToLongTimeString: " + MyDate.ToLongTimeString + "<BR>"  OurLabel.Text += "MyDate.ToShortDateString: " + MyDate.ToShortDateString + "<BR>"  OurLabel.Text += "MyDate.ToLongDateString: " + MyDate.ToLongDateString + "<BR>"  OurLabel.Text += "MyDate.AddDays(2): " + MyDate.AddDays(2) + "<BR>"  OurLabel.Text += "MyDate.AddMonth(4): " + MyDate.AddMonths(4) + "<BR>"  OurLabel.Text += "MyDate.AddYear(1): " + MyDate.AddYears(1) + "<BR>" 
C# datetime_cs.aspx
DateTime MyDate = DateTime.Now;  OurLabel.Text = "MyDate: " + MyDate + "<BR><BR>";  OurLabel.Text += "<B><U>Date Properties:</U></B><BR>";  OurLabel.Text += "MyDate.Hour: " + MyDate.Hour + "<BR>";  OurLabel.Text += "MyDate.Day: " + MyDate.Day + "<BR>";  OurLabel.Text += "MyDate.DayOfWeek: " + MyDate.DayOfWeek + "<BR>";  OurLabel.Text += "MyDate.DayOfYear: " + MyDate.DayOfYear + "<BR>";  OurLabel.Text += "MyDate.Month: " + MyDate.Month + "<BR>";  OurLabel.Text += "MyDate.Year: " + MyDate.Year + "<BR><BR>";  OurLabel.Text += "<B><U>Date Methods:</U></B><BR>";  OurLabel.Text += "MyDate.ToShortTimeString: " + MyDate.ToShortTimeString() + "<BR>";  OurLabel.Text += "MyDate.ToLongTimeString: " + MyDate.ToLongTimeString() + "<BR>";  OurLabel.Text += "MyDate.ToShortDateString: " + MyDate.ToShortDateString() + "<BR>";  OurLabel.Text += "MyDate.ToLongDateString: " + MyDate.ToLongDateString() + "<BR>";  OurLabel.Text += "MyDate.AddDays(2): " + MyDate.AddDays(2) + "<BR>";  OurLabel.Text += "MyDate.AddMonth(4): " + MyDate.AddMonths(4) + "<BR>";  OurLabel.Text += "MyDate.AddYear(1): " + MyDate.AddYears(1) + "<BR>"; 

As you can see in Figure 3.7, there is a lot of built-in functionality for formatting and manipulating dates and times. Figure 3.7 displays the original date we are working with, and then displays some of the available properties and methods. In this example, in the browser window you can see the time on top, then a label for MyDate.PropertyOrMethod to tell you what we are displaying, and then that property or method displayed as described. In the code examples a ToString() method is applied to all of these, so they can be concatenated into one string and displayed in the label. If you are going to use any of these properties and methods to manipulate your dates or times, and want to append them to a string, you must use the ToString() method as well.

Figure 3.7. The DateTime object provides many of the necessary properties and methods to extract and manipulate dates and times in just about any way you would need.
graphics/03fig07.gif


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net