Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

Investigating The String Object

The Pig Latin program manipulates text. As you recall from Chapter 1, “Basic Input and Output: A Mini Adventure,” most programmers, including those who program in C#, refer to text variables as strings. C# provides a special object called the String which manipulates text values in a number of ways. After you understand how a String object works and how it relates to text, you can capitalize the text, search for one phrase inside another, find out the length of the text, and many other things.

The String Mangler Program

The String Mangler program is a silly program that demonstrates ways you can fold, spindle, and mutilate an innocent string variable. I started by defining a string variable and then did some interesting things with it.

Take a look at the program in Figure 3.2 to see what you can do with strings in C#.

Figure 3.2: You can do many interesting things with string variables, including converting to upper and lower case, searching for a phrase, and determining the length of a phrase.

I started with a string that contains the title of this book. (Catchy, huh?) I then did a few simple manipulations of the string. First, I printed it out without any changes. On the next line, I converted it entirely to lowercase and then entirely to uppercase. Next, I replaced the pound sign (#) with the word sharp, and I figured out where the word for occurs in the title of the book. You can do a lot more with string values, but these examples illustrate the possibilities.

A Closer Look at Strings

C# is an object−oriented programming language. You will learn the implications of object−oriented programming as you progress through this book. One implication of object−oriented programming in C# is that you encounter mostly objects. In the first chapter you learned about string variables. The term string is just the programmer’s way of saying text. Most languages have a special type of variable for handling strings. In C#, a string variable is actually an object, which

is a little more powerful than a normal variable. Regular variables contain only data, but objects can have data (like the text in a String object) and commands for manipulating the data. The String object has several very important properties and methods. Programming in C# is focused on learning about the various objects the language provides to you. In particular, if you want to manipulate text, you’ll need to know how to use the String object.

56

Hint Although I am showing you how to learn more about the String object in this section, the real lesson is much broader than that. All the interesting variables and commands in C# are related to objects, so one key to becoming a good C# programmer is learning how to investigate the various objects you encounter. Fortunately, the IDE (Integrated Debugging Environment) provides powerful tools for learning about the objects in the .NET system. After you learn use these tools (such as the Object Browser, which I discuss next), you will find your path to C# proficiency reasonably straight.

Using the Object Browser

In the previous chapters I showed you how to use the .NET SDK documentation and the online help within the editor to learn about objects in C#. However, there is another method, and most programmers find it more convenient. Figure 3.3 demonstrates the Object Browser, an important tool of the Visual Studio environment.

Figure 3.3: The Object Browser enables you to get online help on objects quickly.

You can reach the Object Browser in the IDE by selecting View, Other Windows or pressing Ctrl+Alt+J. All the objects available to your program are accessible from this tool. You find the .NET objects (such as string) under the mscorlib (Microsoft Core Library) branch of the tree. This is usually the first element visible in the Object Browser. Again, understanding the relationship between namespaces and objects is critical. The mscorlib is the library of all .NET objects. Open this library by clicking on its name, and you see a list of the namespaces. Find the System namespace, and you see a list of objects in the namespace.

The String object is an element of the System namespace. When you click the word String in the Objects tree, you see a list in the Members panel on the right. This shows the characteristics, or properties, of the String object.

The string object also has methods. Properties describe an object, and methods are actions the object can take. Put another way, properties are adjectives, and methods are verbs related to a specific object.

57

Take a careful look at the properties and methods of the string object. The String Mangler program uses these string characteristics to do its magic.

In the Real World

Understanding C# might be easier if you envision a more concrete object. OOP programmers create a world populated by various types of objects. Shortly, you will start to build objects of your own. Thinking ahead to that process might help you understand how properties and methods work. If you wanted to build a cow object, for example (really, I’ve done it, in an odd set of circumstances), you would start by thinking about a cow’s properties (age, breed, gender) and its methods (giveMilk, Moo, chewCud). The string object isn’t quite as fun to think about as the cow object, but it works the same way. The designers of C# thought about the characteristics a string should have and made those into properties. They also thought about what a string should do and made those actions into methods. Understanding this is important because you frequently use premade objects in C#. Soon enough, you’ll be making your own objects, and your objects will have properties and methods. It will make a little more sense after you have made a few objects of your own starting in the next chapter.

Experimenting with String Methods

Take a look at the source code of the String Mangler program, and you’ll see how the String Mangler works its magic:

using System;

namespace StringMangler

{

///<summary>

///Demonstrates some of the methods of the String object

///by Andy Harris, 11/16/01

///</summary>

class mangler

{

static void Main(string[] args)

{

string theString = "C# Programming for Absolute Beginners"; Console.WriteLine("default: \t {0}", theString); Console.WriteLine("lowercase: \t {0}", theString.ToLower()); Console.WriteLine("uppercase: \t {0}", theString.ToUpper()); Console.WriteLine("replace: \t {0}", theString.Replace("#", "sharp")); Console.WriteLine("length: \t {0}", theString.Length);

Console.WriteLine("\"for\" occurs at character {0}", theString.IndexOf("for"));

Console.WriteLine();

Console.WriteLine();

Console.WriteLine("Please press enter key to quit");

Console.ReadLine();

} // end main } // end class

}// end namespace

The first part of the program simply creates a string variable named theString and prints it to the screen in the normal way. The next line prints a modified version of the string to the screen. Here is the only part of the code that is new:

58

theString.ToLower();

Remember that theString is a string variable. Because it’s also a string object, it has access to all the methods and properties of a string from the .NET library. Therefore, theString.ToLower() converts theString to lowercase. Of course, you probably guessed that. One benefit of object−oriented programming is increased ease of reading. The ToLower() method converts a string to lowercase. To be sure, take a look at the Object Browser for the string object, and look at the ToLower() method. (There are two versions of this method, but ignore the one that mentions Globalization.CultureInfo.) You can see a concise definition of this method, giving you a good hint about what the method does. If you need more information, you can always go to the online help.

In the Real World

You might wonder why I mention the Object Browser at all if everything in it is more completely described in the online help. I do so because the complete help system for .NET is massive, and almost nobody installs the entire thing on his or her own computer. It’s common to be without the MSDN CDs or Web access at a critical point. The information in the Object Browser is always available, even if you’re on somebody else’s machine without the online help installed. Besides, when you know what you’re looking for, the information on the Object Browser is usually enough to get you started.

Performing Common String Manipulations

The ToUpper() and ToLower() methods are used to change the case of a string, which is especially useful when you want to compare two strings. C# is very picky about case when comparing string values; therefore, "whoo hoo" is not considered the same as "WHOO HOO". If you want to check for a string input, but you don’t care what case it was written in, you can write code like this:

Console.Write ("Please enter an exclamation"); theString = Console.ReadLine();

if (theString.ToUpper() == "WHOO HOO"){ Console.WriteLine("That's a great saying!");

} // end if

Trap If you are using the ToUpper() method on a value you’re comparing, make sure that you compare it to a string that’s also entirely uppercase. If the condition in the preceding code fragment looked like this, if (theString.ToUpper() == "Whoo Hoo"){ the condition would always evaluate to false because any string that is converted to uppercase will never match a string with lowercase characters in it.

The String Mangler program illustrates some other interesting string manipulations. The replace() method is used to replace one value with another. I used it to replace the sharp sign (#) with the word sharp. This feature is handy if you are writing a program that automatically manipulates text files, for example. The length property returns how many characters the string has. This is especially useful if you want to look at the phrase one character at a time.

Finally, the indexOf() method gives you the ability to search for one string inside another. If the search string is not found, the method returns a –1. If the search string is located, the method returns the position in the string where the search string is found.

Trap If you look carefully at the output, you might be surprised by the result of the indexOf() method. It indicates that for occurs at character 15 of C# Programming for

59

Соседние файлы в предмете Программирование на C++