Stringing in the Key of C# - Pdf 63

Chapter 9
Stringing in the Key of C#
In This Chapter

Pulling and twisting a string — but you still can’t push it

Parsing strings read into the program

Formatting output strings manually or using the
String.Format()
method
F
or many applications, you can treat a
string
like one of the built-in
value-type variable types such as
int
or
char
. Certain operations that
are otherwise reserved for these intrinsic types are available to strings, as
follows:
int i = 1; // declare and initialize an int
string s = “abc”; // declare and initialize a string
In other respects, shown as follows, a
string
is treated like a user-defined
class:
string s1 = new String();
string s2 = “abcd”;
int nLengthOfString = s2.Length;

type has a corresponding class
Int32
,
double
has the class
Double
, and so on. The distinction here is that
string
and
String
really are the same thing.
15_597043 ch09.qxd 9/20/05 2:01 PM Page 187
Performing Common Operations
on a String
C# programmers perform more operations on strings than Beverly Hills plastic
surgeons do on Hollywood hopefuls. Virtually every program uses the “addi-
tion” operator that’s used on
string
s, as shown in the following example:
string sName = “Randy”;
Console.WriteLine(“His name is “ + sName); // means concatenate
The
String
class provides this special operator. However, the
String
class
also provides other, more direct methods for manipulating strings. You can
see the complete list by looking up
“String class”
in the Help Index.

{
class Program
{
public static void Main(string[] args)
{
// create a student object
Student s1 = new Student();
s1.sName = “Jenny”;
// now make a new object with the same name
Student s2 = new Student();
s2.sName = s1.sName;
// “changing” the name in the s1 object does not
188
Part III: Object-Based Programming
15_597043 ch09.qxd 9/20/05 2:01 PM Page 188
// change the object itself because ToUpper() returns
// a new string without modifying the original
s2.sName = s1.sName.ToUpper();
Console.WriteLine(“s1 - {0}, s2 - {1}”, s1.sName, s2.sName);
// wait for user to acknowledge the results
Console.WriteLine(“Press Enter to terminate...”);
Console.Read();
}
}
// Student - we just need a class with a string in it
class Student
{
public string sName;
}
}

constants. A string
such as
“this is a string”
is a form of a
string
constant, just like 1 is an
int
constant. In the same way that I reuse my shirts to reduce the size of my
wardrobe, a compiler may choose to combine all accesses to the single con-
stant
“this is a string”
. Reusing
string
constants can reduce the foot-
print of the resulting program but would be impossible if a
string
could be
modified.
Equality for all strings:
The Compare() method
Numerous operations treat a string as a single object — for example, the
Compare()
method.
Compare()
, with the following properties, compares two
strings as if they were numbers:
ߜ If the left-hand string is greater than the right string,
Compare()
returns a 1.
ߜ If the left-hand string is less than the right string, it returns a –1.

“abbd”
, and
“abcde”
is greater than
“abcd”
.
More often than not, you don’t care whether one string is greater than the
other, but only whether the two strings are equal.
You do want to know which string is “bigger” when performing a sort.
The
Compare()
operation returns a 0 when two strings are identical. The fol-
lowing test program uses the equality feature of
Compare()
to perform a cer-
tain operation when the program encounters a particular string or strings.
BuildASentence
prompts the user to enter lines of text. Each line is concate-
nated to the previous line to build a single sentence. This program exits if the
user enters the word EXIT, exit, QUIT, or quit:
// BuildASentence - the following program constructs sentences
// by concatenating user input until the user
// enters one of the termination characters -
//
// this program shows when you need to look for
// string equality
using System;
namespace BuildASentence
{
public class Program

Console.WriteLine(“Press Enter to terminate...”);
Console.Read();
}
// IsTerminateString - return a true if the source
// string is equal to any of the termination strings
public static bool IsTerminateString(string source)
{
string[] sTerms = {“EXIT”, “exit”, “QUIT”, “quit” };
// compare the string entered to each of the
// legal exit commands
foreach(string sTerm in sTerms)
{
// return a true if you have a match
if (String.Compare(source, sTerm) == 0)
{
return true;
}
}
return false;
}
}
}
After prompting the user for what the program expects, the program creates
an empty initial sentence string
sSentence
. From there, the program enters
an “infinite” loop.
191
Chapter 9: Stringing in the Key of C#
15_597043 ch09.qxd 9/20/05 2:01 PM Page 191

starts with
Is
,
Has
,
Can
, or some similar word. In this case,
the name of the function
IsTerminateString()
implies the question, “Is
sLine
a terminate string?” Of course, this is a human convention only — C#
doesn’t care.
If
sLine
is not one of the terminate strings, it is concatenated to the end of
the sentence using the
String.Concat()
function. The program outputs the
immediate result just so the user can see what’s going on.
The
IsTerminateString()
method defines an array of strings
sTerms
. Each
member of this array is one of the strings you’re looking for. Any of these
strings causes the program to return a
true
, which causes the program to
quit faster than a programmer forced to write COBOL.

Each line you entered will be added to a
sentence until you enter EXIT or QUIT
Enter a string
Programming with
You’ve entered: Programming with
Enter a string
C# is fun
You’ve entered: Programming with C# is fun
192
Part III: Object-Based Programming
15_597043 ch09.qxd 9/20/05 2:01 PM Page 192
Enter a string
(more or less)
You’ve entered: Programming with C# is fun (more or less)
Enter a string
EXIT
Total sentence:
Programming with C# is fun (more or less)
Press Enter to terminate...
I have flagged my input in bold to make the output easier to read.
Would you like your compares
with or without case?
The
Compare()
method used within
IsTerminateString()
considers
“EXIT”
and
“exit”

doesn’t even use an
if
statement. The
bool
expression returns the calculated value directly to the user — it gets the
if
out.
What if I want to switch case?
I almost hate to bring it up, but you can use the
switch()
control to look for
a particular string. Usually, you use the
switch()
control to compare a
193
Chapter 9: Stringing in the Key of C#
15_597043 ch09.qxd 9/20/05 2:01 PM Page 193
counting number to some set of possible values; however, the
switch()
does
work on
string
objects, as well. The following version of
IsTerminate
String()
uses the
switch()
control:
// IsTerminateString - return a true if the source
// string is equal to any of the termination strings

Your programs can read strings as if they were arrays of characters using
either the
foreach
control or the index operator
[]
. The following
StringToCharAccess
program demonstrates this technique:
// StringToCharAccess - access the characters in a string
// as if the string were an array
using System;
namespace StringToCharAccess
{
public class Program
{
public static void Main(string[] args)
{
194
Part III: Object-Based Programming
15_597043 ch09.qxd 9/20/05 2:01 PM Page 194
// read a string in from the keyboard
Console.WriteLine(“Input some random character string.”
+ “Make sure it’s completely random”);
string sRandom = Console.ReadLine();
// first output as a string
Console.WriteLine(“When output as a string: “ + sRandom);
Console.WriteLine();
// now output as a series of characters
Console.Write(“When output using the foreach: “);
foreach(char c in sRandom)

to
do the same thing. The results are as follows:
Input some random character string. Make sure it’s completely random
Stephen Davis is one handsome individual
When output as a string: Stephen Davis is one handsome individual
When output using the foreach: Stephen Davis is one handsome individual
When output using the for: Stephen Davis is one handsome individual
Press Enter to terminate...
In some cases, you don’t want to mess with any white space on either end of
the string. The term white space refers to the characters that don’t normally
display on the screen, for example, space, newline (or \n),and tab (\t).
195
Chapter 9: Stringing in the Key of C#
15_597043 ch09.qxd 9/20/05 2:01 PM Page 195


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status