Working with Strings

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 6.  Storing Information in Variables


Look at the keys of your computer keyboard and you will see a lot of examples of characters, such as numbers, letters, and symbols. Visual Basic .NET provides two data types for working with character data. A Char type variable can store a single character value. The more commonly used String variable stores a group of these characters, usually a piece of text such as a word. As you have already seen in numerous examples, to identify a literal string in Visual Basic code, you use double-quotation marks (") as delimiters:

 Dim MyName As String = "Brian" 

The quotation marks around a string value allow the compiler to separate it from other words, such as variable names. Quotes used to delimit a string are not actually stored with the string. However, a string variable can contain double-quotes:

 MyName = "George ""Machine Gun"" Kelly" 

As you can see from the sample previous line of code, to include a double quote within a string, you simply use double-quotation marks. You also can use the Chr function, which returns a character based on a numeric code:

 MyName = "George " & Chr(34) & "Machine Gun" & Chr(34) & "Kelly" 

The number 34 represents the numeric code for the quote character. Whatever method you use to add quotes to your string, the result is the same. If you were to print or display the example string MyName you would see the following value:

 George "Machine Gun" Kelly 

As you develop your applications, you use strings for many purposes. The better you manipulate the strings that you use, the more professional your programs appear. Visual Basic allows you to be quite flexible as you work with the strings in your programs. In this section, we will review the many functions you can use to manipulate character strings.

String Concatenation

One operation you will frequently perform on a string is concatenation. The concatenation operator, which is the ampersand symbol (&), combines two or more strings of text, similar to the way the addition operator combines two or more numbers. When you combine two strings with the concatenation operator, the second string is appended directly to the end of the first string. The result is a longer string containing the full contents of both source strings. The following lines of code show examples of string concatenation:

 Dim s1 As String = "Ebony"  Dim s2 As String = "Ivory"  s1 = s1 & s2  s1 = s1 & "123"  s1 &= "Hello" & 456 & "7"  s1 &= (2 * 4)  Messagebox.Show(s1) 

As you can see from the examples, you can use the concatenation operator to combine any number of strings or numeric expressions. After the previous lines of code are executed, the string stored in the variable s1would be the following:

 EbonyIvory123Hello45678 

Two concatenation features new in VB .NET are the &=operator and the String.Concat method. The &=operator, demonstrated above, provides a shorthand approach for assigning the result of concatenation operation back to the to the original variable. Concat is a static method in the String class which provides the same functionality as the & operator:

 strFullName = String.Concat(strFirstName, " ", strLastName) 

The Concat method returns a string that represents the concatenation of all of its parameters. The previous line of code uses the static method, which does not require an instance of a string variable. However, Concat by itself (even as a method of a string object) does not alter the value of a string variable unless it is used in an assignment statement.

Note

The standard concatenation operators will suffice for most applications. However, the .NET Framework also provides the StringBuilder class, for extra high-performance. For more information, see the help topic "StringBuilder Class."


Determining the Length of the String

For many operations, you may need to know how many characters are in a string. You might need this information to know whether the string with which you are working will fit in a fixed-length database field. Or, if you are working with individual characters of a string, you may want to make sure that the character number you are referencing is valid. In any case, to determine the length of any string, you use the Length property of the string, as illustrated in the following code sample:

 Dim strName As String = "John Doe"  Dim intNameLength As Integer  'The length of the sample string is 8  intNameLength = strName.Length 

Note that the Length property returns the total count of characters in the string, including white spaces.

Working with Parts of a String

You will find many situations in which you need to work with only part of a string. For example, your company may use internal identification numbers in which characters or groups of characters mean something by themselves. Another example would be taking a string containing someone's complete name and parsing it into separate first and last name fields. You can easily accomplish these tasks by using the Substring method of the String class, which returns characters starting from a specified position in a string.

To use the Substring method, simply pass the starting index of the string and the number of characters you want to extract. If you omit the second argument, Substring will return all characters in the string starting from the specified index.

Note

You may already be familiar with Left, Right, and Mid from previous versions of Visual Basic. The SubString method provides the same functionality in a more object-oriented fashion.


Remember, indexes in VB .NET are zero-based, so to extract characters from the leftmost part of a string, you would need to pass zero as the starting index. The following statement retrieves the first three characters of a string:

 strAreaCode = strPhone.SubString(0,3) 

To retrieve characters from the middle of a string, pass the index of the starting position. (As you will see in a moment, the Instr function provides a way to search a string and return the starting index.)

 strPhone = "901-555-1212"  strPrefix = strPhone.SubString(4,3)     'Returns 555  strLocalNumber = strPhone.SubString(4)  'Returns 555-1212 

Notice that if we omit the second parameter to substring, it returns all of the characters in the string from the index to the end.

To retrieve a specified number of characters from the right side of a string, you will need to subtract from the length of the string to find the starting index:

 strSuffix = strPhone.SubString(strPhone.Length   4) 

The previous line of code returns the rightmost four characters in the string strPhone. However, if the length of the string happens to be less than 4, such as a blank phone number, an exception will occur. Valid indexes in a string are positive and the subtraction from any length less than 4 would result in a negative index being passed to the Substring function. You can safeguard against this exception by making sure your calculated starting index is zero or greater:

 strSuffix = strPhone.SubString(Math.Max(0,strPhone.Length   4)) 

Max is a function available in the Math class we discussed earlier in this chapter.

Changing the Case of a String

Strings are frequently used to store alphabetic characters, such as names. The String class provides a few useful methods used to change the case (or capitalization) of a string. The easiest ones to use are ToUpper and ToLower,which convert the characters in a string to upper- and lowercase, respectively:

 Dim TestString As String = "Easy As 123"  Messagebox.Show(TestString.ToUpper)   'Returns EASY AS 123  Messagebox.Show(TestString.ToLower)   'Returns easy as 123 

Note that white spaces and numbers in the string are not affected, only the characters whose case can be changed.

Although these functions may appear to be somewhat trivial, they actually are quite useful for checking user input against a predefined value or a range of values. If you convert the user's input to uppercase, you can compare it to an uppercase test string, as in the following example:

 Select Case txtOperation.Text.ToUpper     Case "WASH"       ' Do Something     Case "RINSE"       ' Do Something Else     Case "SPIN"       ' Do Something Else Yet     Case Else        MessageBox.Show("Invalid Input!!")  End Select 

Note

The string methods return values, but they do not modify the input. Consider the following example with the ToUpper method:

 Dim s1 As String  Dim s2 As String  s1 = "which case am i"  s2 = s1.ToUpper 

After this code is executed, the variable s2 appears in all uppercase letters, whereas s1 remains unchanged, unless you put s1 on both sides of the assignment statement, like this:

 s1 = s1.ToUpper 


In the preceding code, if the ToUpper method had not been applied to the value of the text box, the user would receive the invalid input message even if he or she had entered a correct choice in lowercase or mixed case (Rinse, for example).

Another Visual Basic function, StrConv, performs special conversions of strings. StrConv can convert a string to proper case, in which the first letter of each word is capitalized. The following code sample demonstrates this technique:

 StrConv("DR. STIRLING P. WILLIAMS", VbStrConv.ProperCase) 

The constant passed as the second parameter to StrConv indicates the type of conversion to perform. Most of the additional conversions are either redundant (converting to all uppercase or all lowercase, for example) or beyond the scope of this book (converting between different types of Japanese characters). The result of the preceding call to StrConv would return a string like the following:

 Dr. Stirling P. Williams 

The proper case conversion handles most names, but suffixes like III would be incorrectly converted to Iii.

Searching a String

For many string-related tasks, the first programming requirement is to determine whether a word, phrase, or other group of characters exists in a string and, if so, where. The capability to find one string within another enables you to perform word searches within text. You can do these searches to perform a global replacement of a string, such as replacing the word catastrophe with the words opportunity for improvement throughout a word processing document.

Another, more common, reason for searching within a string is parsing the string. For example, suppose you have an input string that contains a person's name in this format: "Bobby Lee Schwartz." If you have a file of a hundred such strings, putting this information into a database with separate first and last name fields would be a little difficult. However, you can use a string search function along with a little program logic to parse the string into smaller pieces.

A new function in Visual Basic .NET than be used to search a string for a character or string is the IndexOf method. The IndexOf method has several overloaded parameter lists, but in its simplest form it accepts the search string and returns the index where it starts:

 Dim strSentence As String  Dim intFoundPosition As Integer  strSentence = "I'll see you next Tuesday"  intFoundPosition = strSentence.IndexOf("you") 

If the IndexOf method cannot find the string, it returns the value 1. You can check the return value of IndexOf with an If statement to determine whether the search was successful:

 If intFoundPosition < 0 Then        Debug.WriteLine("I couldn't find you!")  Else        Debug.WriteLine("I found you at position " & intFoundPosition)  End If 

In our example, the IndexOf method should return a value of 9, which is the index of the y in the word you. The index value returned from a search can be used with the other sting functions mentioned in this section to manipulate or change specific characters.

Note

String searches are case-sensitive.


Note

At the time of this writing, the traditional Visual Basic string search function, Instr, was still supported. However, it still uses a 1-based index for string characters. To avoid confusion of string indexes when working with other string functions, the authors recommend using the newer IndexOf method instead.


Another common type of search uses a parameter to tell the IndexOf function the index from which to start the search. For example, the function call

 Debug.WriteLine ("Pride cometh before a fall".IndexOf("e",6)) 

returns the value of 9, even though the first e in the string is at position 4, because the search starts from position 6. You also can specify an ending range for the search by providing an ending index:

 Debug.WriteLine ("Pride cometh before a fall".IndexOf("a",0,10)) 

The extra parameters in the previous line of code instruct the IndexOf function to start the search at index 0 and end the search at index 10, so a search for an a in this range would be unsuccessful. When you use parameters to specify a search range, they must be positive integers within the valid index ranges for the string, or the function will throw an exception.

Before we leave the subject of searching strings, we should mention another function new to .NET, the EndsWith method. It simply returns True or False depending on whether a string ends with a particular set of characters:

 If FilePathName.ToUpper.EndsWith("JPG") Then     FileDescription = "Picture file"  ElseIf filepathname.EndsWith("MP3") Then     FileDescription = "Music File"  End If 

As with the IndexOf method, searches using EndsWith are case sensitive.

Getting Rid of Extra Spaces

It is normal for some strings contain to spaces in the middle of the string, which are necessary for proper spacing of words, paragraphs, and so on. However, you also may end up with spaces at the beginning or end of your strings, which often are unwanted spaces. These spaces typically occur when the user accidentally types a space at the beginning or end of a text field, and can interfere with comparisons:

 Dim s1 As String = "Hello      "  Dim s2 As String = " Hello "  Dim s3 As String = "     Hello" 

Although they contain the same word, the extra spaces in the strings cause them to be nonequivalent, and the Length property of each contains a different value. This difference is especially crucial with text box input; a user could inadvertently type three characters of text and then a bunch of spaces in a text box. If you need to concatenate the input with another string or use it in an If statement, the extra spaces are included. However, Visual Basic provides some string-trimming functions to eliminate the trailing spaces.

To get rid of the spaces at the end of a string, you can use the Trim or TrimEnd methods. The Trim method works with both ends of a string, but TrimEnd only removes spaces from the right:

 "  Test String  ".Trim             'Removes spaces from left and right  "  Test String  ".TrimEnd(Nothing) 'Removes spaces from right only  "x Test String x".Trim             'Does not remove any spaces 

Note

Both Trim and TrimEnd also have the ability to remove characters other than spaces. For example, the following code trims the string rac from both ends of the word racecar, which leaves only an e:

 MessageBox.Show("racecar".Trim("rac".ToCharArray)) 


Trim and TrimEnd work with leading and trailing characters. In other words, if there is a character between the end of the string and the search character, these functions will not trim the character. However, Visual Basic .NET provides two other methods that can be used for removing or substituting characters anywhere in the string: Remove and Replace.

 "Extraordinary".Remove(0,4)     'Returns "ordinary"  "Pop".replace("o"c, "a"c)  'Returns "Pap" 

Remove accepts a start and ending index and returns a string with all characters in the index range removed. Replace replaces each occurrence of a character with another character.

Adding Characters to the Ends of a String

Just as there are times when you don't need any extra spaces in your strings, there are sometimes reasons to pad a string with extra characters. For example, my company bought new Accounts Payable software that required the conversion of vendor identification numbers from a 9-character string with no extra digits to a 10-digit format with leading zeroes. By using the PadLeft and PadRight methods of the String class, this can easily be accomplished:

 strNewVendorNumber = strOldVendorNumber.PadLeft(10, "0"c) 

The first parameter to the PadLeft function is the desired total string length, including padding. The second parameter is the character to pad in order to meet the desired length. Leaving the second parameter off will pad the string with spaces.

PadLeft and PadRight add a single character a repeated number of times to the end of the string. However, there are times when you way want to add a set of characters to the middle of the string. You can accomplish this with the Substring method and concatenation operators, but Visual Basic provides a shortcut: the Insert method. The Insert method inserts a string into another string at the specified index.


    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

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