String Manipulation


Your use of strings so far has consisted of writing strings to the console, reading strings from the console, and concatenating strings using the + operator. In the course of programming more interesting applications, you will soon discover that the manipulation of strings is something that you end up doing a lot. Because of this, it is worth spending a few pages looking at some of the more common string manipulation techniques available in C#.

To start with, it is well worth noting that a string type variable can be treated as a read-only array of char variables. This means that you can access individual characters using syntax like:

 string myString = "A string"; char myChar = myString[1]; 

However, you can't assign individual characters in this way.

To get a char array that you can write to, you can use the following code. This uses the ToCharArray() command of the array variable

 string myString = "A string"; char[] myChars = myString.ToCharArray(); 

and then you can manipulate the char array in the standard way.

You can also use strings in foreach loops, for example:

 foreach (char character in myString) { Console.WriteLine("{0}", character); } 

As with arrays, you can also get the number of elements using myString.Length. This gives you the number of characters in the string, for example:

 string myString = Console.ReadLine(); Console.WriteLine("You typed {0} characters.", myString.Length); 

Other basic string manipulation techniques use commands with a format similar to this <string>. ToCharArray() command. Two simple, but useful, ones are <string>.ToLower() and <string>. ToUpper(). These enable strings to be converted into lower- and uppercase, respectively. To see why this is useful, consider the situation in which you want to check for a specific response from a user, for example the string yes. If you convert the string entered by the user into lowercase, then you can also check for the strings YES, Yes, yeS, and so on — you saw an example of this in the previous chapter if you recall:

 string userResponse = Console.ReadLine(); if (userResponse.ToLower() == "yes") { // Act on response. } 

Note that this command, like the others in this section, doesn't actually change the string to which it is applied. Instead, combining this command with a string results in a new string being created, which you can compare to another string (as shown above) or assign to another variable. This other variable may be the same one that is being operated on, for example:

 userResponse = userResponse.ToLower(); 

This is an important point to remember, because just writing

 userResponse.ToLower(); 

doesn't actually achieve very much!

There are other things you can do to ease the interpretation of user input. What if the user accidentally put an extra space at the beginning or end of their input? In this case, the preceding code won't work. You need to trim the string entered, which you can do using the <string>.Trim() command:

 string userResponse = Console.ReadLine(); userResponse = userResponse.Trim(); if (userResponse.ToLower() == "yes") { // Act on response. } 

Using this, you will also be able detect strings like:

"  YES" "Yes  "

You can also use these commands to remove any other characters, by specifying them in a char array, for example:

 char[] trimChars = {' ', 'e', 's'};  string userResponse = Console.ReadLine(); userResponse = userResponse.ToLower(); userResponse = userResponse.Trim(trimChars); if (userResponse == "y") { // Act on response. } 

This gets rid of any occurrences of spaces, the letter "e," and the letter "s" from the beginning or end of your string. Providing that there isn't any other character in the string, this will result in the detection of strings such as

"Yeeeees" " y"

and so on.

You can also use the <string>.TrimStart() and <string>.TrimEnd() commands, which will trim spaces from the beginning and end of a string, respectively. These can also have char arrays specified.

There are two other string commands that you can use to manipulate the spacing of strings: <string>.PadLeft() and <string>.PadRight(). These allow you to add spaces to the left or right of a string to force it to the desired length. You use these as follows:

 <string>.PadX(<desiredLength>); 

For example:

 myString = "Aligned"; myString = myString.PadLeft(10); 

This would result in three spaces being added to the left of the word Aligned in myString. These methods can be useful for aligning strings in columns, which is particularly useful for placing number strings below others.

As with the trimming commands, you can also use these commands in a second way, by supplying the character to pad the string with. This involves a single char, not an array of chars as with trimming. For example:

 myString = "Aligned"; myString = myString.PadLeft(10, '-'); 

This would add three dashes to the start of myString.

There are many more of these string manipulation commands, many of which are only useful in very specific situations. I'll discuss these as and when you use them in the forthcoming chapters. Before moving on, though, it is worth looking at one of the features of VS that you may have noticed over the course of the last few chapters, and especially this one. In the following Try It Out, you examine auto-completion in VS, where the IDE tries to help you out by suggesting what code you might like to insert.

Try It Out – Statement Auto-completion in VS

image from book
  1. Create a new console application called Ch05Ex05 in the directory C:\BegVCSharp\Chapter5.

  2. Type the following code to Program.cs, exactly as written, noting windows that pop up as you do so.

    static void Main(string[] args) { string myString = "This is a test."; char[] separator = {' '}; string[] myWords; myWords = myString. }
  3. As you type the final period, note that the window shown in Figure 5-12 pops up.

    image from book
    Figure 5-12

  4. Without moving the cursor, type "s". The pop-up window changes, and a yellow tooltip popup appears, as shown in Figure 5-13.

    image from book
    Figure 5-13

  5. Type the following characters: (separator);. The code should look as follows, and the pop-up windows should disappear:

    static void Main(string[] args) {    string myString = "This is a test.";    char[] separator = {' '};    string[] myWords; myWords = myString.Split(separator); }
  6. Add the following code, noting the windows as they pop up:

    static void Main(string[] args) {    string myString = "This is a test.";    char[] separator = {' '};    string[] myWords;    myWords = myString.Split(separator); foreach (string word in myWords) { Console.WriteLine("{0}", word); } Console.ReadKey(); }
  7. Execute the code. The result is shown in Figure 5-14.

    image from book
    Figure 5-14

How It Works

There are two main points to note in this code. The first is the new string command you have used, and the second is the use of the auto-completion function in VS. You will tackle these one at a time.

The command you have used, <string>.Split(), converts a string into a string array by splitting it at the points specified. These points take the form of a char array, which in this case is simply populated by a single element, the space character:

char[] separator = {' '};

The following code obtains the substrings you get when the string is split at each space, that is, you get an array of individual words:

string[] myWords; myWords = myString.Split(separator); 

Next, you loop through the words in this array using foreach and write each one to the console:

foreach (string word in myWords) {    Console.WriteLine("{0}", word); }

Note

Note that each word obtained will have no spaces, neither embedded in the word nor at either end. The separators are removed when you use Split().

Next, on to the auto-completion. VS is a very intelligent package, and works out a lot of information about your code as you type it in. Even as you type the first character on a new line VS tries to help you, by suggesting that you might want to type a keyword, a variable name, a type name, and so on. Only three letters into the preceding code (str), VS has guessed that you want to type string. Even more useful is when you type variable names. In long pieces of code, you often forget the names of variables you want to use. Since VS pops up a list of these as you type, you can work along just fine without having to refer to earlier code.

By the time you type the period after myString, it knows that myString is a string, detects that you want to specify a string command, and presents the available options. At this point, you can stop typing, should you wish to, and select the command you want using the up and down arrow keys. As you move through what is available, VS tells you what the currently selected command means and what the syntax for using it is.

When you start typing more characters VS moves the selected command to the top of the commands you might mean automatically. Once it shows the command you want, you can simply carry on typing as if you'd typed the whole name, so typing " (" takes you straight to the point where you specify the additional information that some commands require — and VS even tells you the format this extra information must be in, presenting options for those commands that accept varying amounts of information.

This feature of VS (also known as IntelliSense) can come in very handy, and allows you to find out information about strange types with ease. You may find it interesting to look at all the commands that the string type exposes and experiment — nothing you do is going to break the computer, so play away!

image from book




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

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