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.
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.");
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.
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. |
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.
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
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.
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.”) |
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);
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.
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:
3.141.47.25