
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
54
|
Chapter 2: Strings and Characters
This code creates a new string and then makes the ID variable refer to it. The string in
ID now looks like this:
This car is the property of Mary.
As when removing a portion of a string, you may, for performance reasons, choose to
use the
Replace method of the StringBuilder class instead. For example:
string newName = "John Doe";
str = new StringBuilder("name = <NAME>");
str.Replace("<NAME>", newName);
Console.WriteLine(str.ToString( ));
str.Replace('=', ':');
Console.WriteLine(str.ToString( ));
str = new StringBuilder("name1 = <FIRSTNAME>, name2 = <FIRSTNAME>");
str.Replace("<FIRSTNAME>", newName, 7, 12);
Console.WriteLine(str.ToString( ));
str.Replace('=', ':', 0, 7);
Console.WriteLine(str.ToString( ));
This code produces the following results:
name = John Doe
name : John Doe
name1 = John Doe, name2 = <FIRSTNAME>
name1 : John Doe, name2 = <FIRSTNAME>
Note that when using the StringBuilder class, you must use the System.Text
namespace.
Discussion
The String class provides two methods that allow easy removal and modification of
characters in a string: the
Remove instance method and the Replace instance method.
The
Remove method deletes a specified number of characters starting at a given loca-
tion within a string. This method returns a new
string object containing ...