Книга: C# 2008 Programmer
String Manipulations
Разделы на этой странице:
String Manipulations
Often, once your values are stored in string variables, you need to perform a wide variety of operations on them, such as comparing the values of two strings, inserting and deleting strings from an existing string, concatenating multiple strings, and so on. The String
class in the .NET Framework provides a host of methods for manipulating strings, some of the important ones of which are explained in the following sections.
You can find out about all of the String
class methods at www.msdn.com.
Testing for Equality
Even though string is a reference type, you will use the ==
and !=
operators to compare the value of two strings (not their references).
Consider the following three string variables:
string str1 = "This is a string";
string str2 = "This is a ";
str2 += "string";
string str3 = str2;
The following statements test the equality of the values contained in each variable:
Console.WriteLine(str1 == str2); //---True---
Console.WriteLine(str1 == str3); //---True---
Console.WriteLine(str2 != str3); //---False---
As you can see from the output of these statements, the values of each three variables are identical. However, to compare their reference equality, you need to cast each variable to object and then check their equality using the == operator, as the following shows:
Console.WriteLine((object)str1 == (object)str2); //---False---
Console.WriteLine((object)str2 == (object)str3); //---True---
However, if after the assignment the original value of the string is changed, the two strings' references will no longer be considered equal, as the following shows:
string str3 = str2;
Console.WriteLine((object)str2 == (object)str3); //---True---
str2 = "This string has changed";
Console.WriteLine((object)str2 == (object)str3); //---False---
Besides using the ==
operator to test for value equality, you can also use the Equals()
method, which is available as an instance method as well as a static method:
Console.WriteLine(str1 == str2); //---True---
Console.WriteLine(str1.Equals(str2)); //---True---
Console.WriteLine(string.Equals(str1,str2)); //---True---
Comparing Strings
String comparison is a common operation often performed on strings. Consider the following two string variables:
string str1 = "Microsoft";
string str2 = "microsoft";
You can use the String.Compare()
static method to compare two strings:
Console.WriteLine(string.Compare(str1, str2)); // 1;str1 is greater than str2
Console.WriteLine(string.Compare(str2, str1)); // -1;str2 is less than str1
Console.WriteLine(string.Compare(str1, str2, true)); // 0;str1 equals str2
The lowercase character "m" comes before the capital "M," and hence str1
is considered greater than str2
. The third statement compares the two strings without considering the casing (that is, case-insensitive; it's the third argument that indicates that the comparison should ignore the casing of the strings involved).
The String.Compare()
static method is overloaded, and besides the two overloaded methods (first two statements and the third statement) just shown, there are additional overloaded methods as described in the following table.
Method | Description |
---|---|
Compare(String, String) |
Compares two specified String objects. |
Compare(String, String, Boolean) |
Compares two specified String objects, ignoring or respecting their case. |
Compare(String, String, StringComparison) |
Compares two specified String objects. Also specifies whether the comparison uses the current or invariant culture, honors or respects case, and uses word or ordinal sort rules. |
Compare(String, String, Boolean, CultureInfo) |
Compares two specified String objects, ignoring or respecting their case, and using culture-specific information for the comparison. |
Compare(String, Int32, String, Int32, Int32) |
Compares substrings of two specified String objects. |
Compare(String, Int32, String, Int32, Int32, Boolean) |
Compares substrings of two specified String objects, ignoring or respecting their case. |
Compare(String, Int32, String, Int32, Int32, StringComparison) |
Compares substrings of two specified String objects. |
Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) |
Compares substrings of two specified String objects, ignoring or respecting their case, and using culture-specific information for the comparison. |
Alternatively, you can use the CompareTo()
instance method, like this:
Console.WriteLine(str1.CompareTo(str2)); // 1; str1 is greater than str2
Console.WriteLine(str2.CompareTo(str1)); // -1; str2 is less than str1
Note that comparisons made by the CompareTo()
instance method are always case sensitive.
Creating and Concatenating Strings
The String
class in the .NET Framework provides a number of methods that enable you to create or concatenate strings.
The most direct way of concatenating two strings is to use the "+
" operator, like this:
string str1 = "Hello ";
string str2 = "world!";
string str3 = str1 + str2;
Console.WriteLine(str3); //---Hello world!---
The String.Format()
static method takes the input of multiple objects and creates a new string. Consider the following example:
string Name = "Wei-Meng Lee";
int age = 18;
string str1 = string.Format("My name is {0} and I am {1} years old", Name, age);
//---str1 is now "My name is Wei-Meng Lee and I am 18 years old"---
Console.WriteLine(str1);
Notice that you supplied two variables of string and int type and the Format()
method automatically combines them to return a new string.
The preceding example can be rewritten using the String.Concat()
static method, like this:
string str1 =
string.Concat("My name is ", Name, " and I am ", age, " years old");
//---str1 is now "My name is Wei-Meng Lee and I am 18 years old"---
Console.WriteLine(str1);
Strings Are Immutable
In .NET, all string objects are immutable. This means that once a string variable is initialized, its value cannot be changed. And when you modify the value of a string, a new copy of the string is created and the old copy is discarded. Hence, all methods that process strings return a copy of the modified string — the original string remains intact.
For example, the Insert()
instance method inserts a string into the current string and returns the modified string:
str1 = str1.Insert(10, "modified ");
In this statement, you have to assign the returned result to the original string to ensure that the new string is modified.
The String.Join()
static method is useful when you need to join a series of strings stored in a string array. The following example shows the strings in a string array joined using the Join()
method:
string[] pts = { "1,2", "3,4", "5,6" };
string str1 = string.Join("|", pts);
Console.WriteLine(str1); //---1,2|3,4|5,6---
To insert a string into an existing string, use the instance method Insert(), as demonstrated in the following example:
string str1 = "This is a string";
str1 = str1.Insert(10, "modified ");
Console.WriteLine(str1); //---This is a modified string---
The Copy()
instance method enables you to copy part of a string into a char array. Consider the following example:
string str1 = "This is a string";
char[] ch = { '*', '*', '*', '*', '*', '*', '*', '*' };
str1.CopyTo(0, ch, 2, 4); Console.WriteLine(ch); //---**This**---
The first parameter of the CopyTo()
method specifies the index of the string to start copying from. The second parameter specifies the char array. The third parameter specifies the index of the array to copy into, while the last parameter specifies the number of characters to copy.
If you need to pad a string with characters to achieve a certain length, use the PadLeft()
and PadRight()
instance methods, as the following statements show:
string str1 = "This is a string"; string str2;
str2 = str1.PadLeft(20, '*');
Console.WriteLine(str2); //---"****This is a string"---
str2 = str1.PadRight(20, '*');
Console.WriteLine(str2); //---"This is a string****"---
Trimming Strings
To trim whitespace from the beginning of a string, the end of a string, or both, you can use the TrimStart()
, TrimEnd()
, or Trim()
instance methods, respectively. The following statements demonstrate the use of these methods:
string str1 = " Computer ";
string str2;
Console.WriteLine(str1); //---" Computer "---
str2 = str1.Trim();
Console.WriteLine(str2); //---"Computer"---
str2 = str1.TrimStart();
Console.WriteLine(str2); //---"Computer "---
str2 = str1.TrimEnd();
Console.WriteLine(str2); //---" Computer"---
Splitting Strings
One common operation with string manipulation is splitting a string into smaller strings. Consider the following example where a string contains a serialized series of points:
string str1 = "1,2|3,4|5,6|7,8|9,10";
Each point ("1, 2", "3, 4", and so on) is separated with the | character. You can use the Split()
instance method to split the given string into an array of strings:
string[] strArray = str1.Split('|');
Once the string is split, the result is stored in the string array strArray
and you can print out each of the smaller strings using a foreach
statement:
foreach (string s in strArray) Console.WriteLine(s);
The output of the example statement would be:
1,2
3,4
5,6
7,8
9,10
You can further split the points into individual coordinates and then create a new Point
object, like this:
string str1 = "1,2|3,4|5,6|7,8|9,10";
string[] strArray = str1.Split('|');
foreach (string s in strArray) {
string[] xy= s.Split(',');
Point p = new Point(Convert.ToInt16(xy[0]), Convert.ToInt16(xy[1]));
Console.WriteLine(p.ToString());
}
The output of the above statements would be:
{X=1,Y=2}
{X=3,Y=4}
{X=5,Y=6}
{X=7,Y=8}
{X=9,Y=10}
Searching and Replacing Strings
Occasionally, you need to search for a specific occurrence of a string within a string. For this purpose, you have several methods that you can use.
To look for the occurrence of a word and get its position, use the IndexOf()
and LastIndexOf()
instance methods. IndexOf()
returns the position of the first occurrence of a specific word from a string, while LastIndexOf()
returns the last occurrence of the word. Here's an example:
string str1 = "This is a long long long string...";
Console.WriteLine(str1.IndexOf("long")); //---10---
Console.WriteLine(str1.LastIndexOf("long")); //---20---
To find all the occurrences of a word, you can write a simple loop using the IndexOf()
method, like this:
int position = -1;
string str1 = "This is a long long long string...";
do {
position = str1.IndexOf("long", ++position);
if (position > 0) Console.WriteLine(position);
} while (position > 0);
This prints out the following:
10
15
20
To search for the occurrence of particular character, use the IndexOfAny()
instance method. The following statements search the str1
string for the any of the characters a, b, c, d, or e, specified in the char
array:
char[] anyof = "abcde".ToCharArray();
Console.WriteLine(str1.IndexOfAny(anyof)); //---8---
To obtain a substring from within a string, use the Substring()
instance method, as the following example shows:
string str1 = "This is a long string...";
string str2;
Console.WriteLine(str1.Substring(10)); //---long string...---
Console.WriteLine(str1.Substring(10, 4)); //---long---
To find out if a string begins with a specific string, use the StartsWith()
instance method. Likewise, to find out if a string ends with a specific string, use the EndsWith()
instance method. The following statements illustrate this:
Console.WriteLine(str1.StartsWith("This")); //---True---
Console.WriteLine(str1.EndsWith("...")); //---True---
To remove a substring from a string beginning from a particular index, use the Remove() instance method:
str2 = str1.Remove(10);
Console.WriteLine(str2); //---"This is a"---
This statement removes the string starting from index position 10. To remove a particular number of characters, you need to specify the number of characters to remove in the second parameter:
str2 = str1.Remove(10,5); //---remove 5 characters from index 10---
Console.WriteLine(str2); //---"This is a string..."---
To replace a substring with another, use the Replace()
instance method:
str2 = str1.Replace("long", "short");
Console.WriteLine(str2); //---"This is a short string..."---
To remove a substring from a string without specifying its exact length, use the Replace()
method, like this:
str2 = str1.Replace("long ", string.Empty);
Console.WriteLine(str2); //---"This is a string..."---
Changing Case
To change the casing of a string, use the ToUpper()
or ToLower()
instance methods. The following statements demonstrate their use:
string str1 = "This is a string"; string str2;
str2 = str1.ToUpper();
Console.WriteLine(str2); //---"THIS IS A STRING"---
str2 = str1.ToLower();
Console.WriteLine(str2); //---"this is a string"---
- The System.String Class
- Whole Sequence Manipulations
- Using Double Quotes to Resolve Variables in Strings with Embedded Spaces
- Special String Constants
- More on Strings
- Strings
- Searches for a String in Input with grep
- Using the Backtick to Replace a String with Output
- String Comparison
- 13.6.3. strings
- Chapter 8 Strings and Regular Expressions
- ToString() Method