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:
Читать дальше