Manipulating Strings

   

Recall from the previous hour that a string is text. Although string manipulation isn't technically arithmetic, the things that you do with strings are very similar to things you do with numbers , such as adding two strings together; string manipulation is much like creating equations. Chances are you'll be working with strings a lot in your applications. C# includes a number of methods that enable you to do things with strings, such as retrieve a portion of a string or find one string within another. In the following sections, you'll learn the basics of string manipulation.

Concatenating Strings of Text

graphics/newterm.gif

C# makes it possible to "add" two strings of text together to form one string. Although purists will say it's not truly a form of arithmetic, it's very much like performing arithmetic on strings, so this hour was the logical place in which to present this material. The process of adding two strings together is called concatenation. Concatenation is very common. For example, you may want to concatenate variables with hard-coded strings to display meaningful messages to the user , such as Are you sure you wish to delete the user XXX? , where XXX is the contents of a variable.

To concatenate two strings, you use the + operator as shown in this line of code:

 Debug.WriteLine("This is" + "a test."); 

This statement would print:

 This isa test. 

Notice that there is no space between the words is and a. You could easily add a space by including one after the word is in the first string or before the a in the second string, or you could concatenate the space as a separate string, like this:

 Debug.WriteLine("This is" + " " + "a test."); 
graphics/newterm.gif

Text placed directly within quotes is called a literal. Variables are concatenated in the same way as literals and can even be concatenated with literals. The following code creates two variables, sets the value of the first variable to "Allan," and sets the value of the second variable to the result of concatenating the variable with a space and the literal "Reed":

 string strFullName; string strFirstName = "Allan"; strFullName = strFirstName + " " + "Reed"; 

The final result is that the variable strFullName contains the string Allan Reed. Get comfortable concatenating strings of text ”you'll do this often.

graphics/bookpencil.gif

In C#, strings are immutable. What this means is that they never change. When you concatenate two strings together, neither is modified; instead a new string is created. Eventually, the garbage collector (discussed in Hour 24, "The 10,000-Foot View") will clean up the unused strings. However, if you're going to be concatenating a lot of strings, this could have an adverse effect on system resources (until the garbage collector springs into action). C# includes a highly efficient way to concatenate strings via System.Text. StringBuilder . Although I can't go into the details here, I highly encourage you to research this if you plan to concatenate a lot of strings at once.

Using the Basic String Methods and Properties

The .NET Framework includes a number of functions that make working with strings of text considerably easier than it might be otherwise . These functions let you easily retrieve a piece of text from a string, compute the number of characters in a string, and even determine whether one string contains another. The following sections summarize the basic string functions.

Determining the Number of Characters Using Length

The Length property of the string object returns the variable's length. The following statement prints 26 , the total number of characters in the literal string "Pink Floyd reigns supreme." Remember, the quotes that surround the string tell C# that the text within them is a literal; they are not part of the string.

 Debug.WriteLine(("Pink Floyd reigns supreme.").Length);     // Prints 26 
Retrieving Text from a String Using the Substring() Method

The Substring() method retrieves a part of a string.

The Substring() method can be used with the following parameters:

 public string Substring(  startposition,   numberofcharacters  ); 

For example, the following statement prints Queen , the first five characters of the string.

 Debug.WriteLine(("Queen to Queen's Level Three.").Substring(0,5)); 

The arguments used in this Substring example are 0 and 5. The 0 indicates starting at the 0 position of the string (beginning). The 5 indicates the specified length to return (characters to retrieve).

The Substring() method is commonly used with the IndexOf() method (discussed shortly) to retrieve the path portion of a variable containing a filename and path combination, such as c:\Myfile.txt . If you know where the \character is, you can use Substring() to get the path.

graphics/bookpencil.gif

If the number of characters requested is greater than the number of characters in the string, an exception (error) occurs. If you're unsure about the number of characters in the string, use the Length property of the string to find out. (Exception handling is reviewed in Hour 16, "Debugging Your Code.")

Determining Whether One String Contains Another Using IndexOf() Method

At times you'll need to determine whether one string exists within another. For example, suppose you let users enter their full name into a text box, and that you want to separate the first and last names before saving them into individual fields in a database. The easiest way to do this is to look for the space in the string that separates the first name from the last. You could use a loop to examine each character in the string until you find the space, but C# includes a string method that does this for you, faster and easier than you could do it yourself: the IndexOf() method. The basic IndexOf() method has the following syntax:

 MyString.IndexOf(  searchstring  ); 

The IndexOf() method of a string searches the string for the occurrence of a string passed as an argument. If the string is found, the location of character at the start of the string is returned. If the search string is not found within the other string, -1 is returned. The IndexOf() method can be used with the following arguments:

  • public int IndexOf( searchstring );

  • public int IndexOf( searchstring, startinglocation );

  • public int IndexOf( searchstring, startinglocation, numberofcharacterstosearch);

The following code searches a variable containing the text "Jayson Goss" , locates the space, and uses the Substring() method and Length property to place the first and last names in separate variables.

 string strFullName = "Jayson Goss"; string strFirstName, strLastName; int intLocation, intLength; intLength = strFullName.Length; intLocation = strFullName.IndexOf(" "); strFirstName = strFullName.Substring(0,intLocation ); strLastName = strFullName.Substring(intLocation + 1); 
graphics/bulb.gif

This code assumes that a space will be found and that it won't be the first or last character in the string. In your applications, your code may need to be more robust, including checking to ensure that IndexOf() returned a value other than -1 , which would indicate that no space was found.

When this code runs, IndexOf() returns 6, the location in which the first space is found. Notice how I subtracted an additional character when using SubString() to initialize the strLastName variable; this was to take the space into account.

Trimming Beginning and Trailing Spaces from a String

As you work with strings, you'll often encounter situations in which spaces exist at the beginning or ending of strings. The .NET Framework includes the following four methods for automatically removing spaces from the beginning or end of a string:

Method Description
String.Trim Removes white spaces from the beginning and end of a string.
String.TrimEnd Removes characters specified in an array of characters from the end of a string.
String.TrimStart Removes characters specified in an array of characters from the beginning of a string.
String.Remove Removes a specified number of characters from a specified index position in a string.

   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

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