In C#, the string type is used for processing multiple character Unicode character data. (The char type, by comparison, is a value type that handles single characters.)
The type name string is a shortened name for the System.String class. The compiler can process this shortened form; therefore string and System.String can be used interchangeably.
The String class represents an immutable string of characters. An instance of String is immutable: the text of a string cannot be modified after it has been created. Methods that might appear at first sight to modify a string value actually return a new instance of string that contains the modification.
The StringBuilder class is often used in partnership with the String class. A StringBuilder builds an internally modifiable string that can be converted into an immutable String when complete. StringBuilder removes the need to repeatedly create temporary immutable Strings and can provide improved performance.
The System.String class has many methods. I will list some of the more useful methods. For further details, consult the .NET Framework software development kit (SDK) Help documents.
Common String Methods, Operators, and Properties
Brackets [ ]
You can extract a single character at a given position in a string by using the string name followed by the index in brackets ([ and ]). This process is similar to using an array. The first character in the string has an index of zero. The following code provides an example:
string s = “Alphabet”;
char firstchar = s[2]; // ‘p’
Strings are immutable, so assigning a character by using brackets is not permitted. Any attempt to assign a character to a string in this way will generate a compile-time error, as shown:
s[2] = ‘*’; // Not valid
Insert Method
If you want to insert characters into a string variable, use the Insert instance method to return a new string with a specified value inserted at a specified position in this string. This method takes two parameters: the position of the start of the insertion and the string to insert. The following code provides an example:
string s = “C is great!”;
s = s.Insert(2, “Sharp “);
Console.WriteLine(s); // C Sharp is great!
Length Property
The Length property returns the length of a string as an integer, as shown:
string msg = “Hello”;
int slen = msg.Length; // 5
Copy Method
The Copy class method creates a new string by copying another string. The Copy method makes a duplicate of a specified string. The following code provides an example:
string s1 = “Hello”;
string s2 = String.Copy(s1);
Concat Method
The Concat class method creates a new string from one or more strings or objects represented as strings. The following code provides an example:
string s3 = String.Concat(“a”, “b”, “c”, “d”, “e”, “f”, “g”);
The + operator is overloaded for strings, so the example above can be re-written as follows:
string s = “a” + “b” + “c” + “d” + “e” + “f” + “g”;
Console.WriteLine(s);
Trim Method
The Trim instance method removes all of the specified characters or white space from the beginning and end of a string. The following code provides an example:
string s = ” Hello “;
s = s.Trim();
Console.WriteLine(s); // “Hello”
ToUpper and ToLower Methods
The ToUpper and ToLower instance methods return a string with all characters converted to uppercase and lowercase, respectively, as shown:
string sText = “How to Succeed “;
Console.WriteLine(sText.ToUpper()); // HOW TO SUCCEED
Console.WriteLine(sText.ToLower()); // how to succeed
String Comparisons
You can use the == and != operators on string variables to compare string contents.
Equals Method
The System.String class contains an instance method called Equals, which can be used to compare two strings for equality. The method returns a bool value that is true if the strings are the same and false otherwise. This method is overloaded and can be used as an instance method or a static method. The following example shows both forms.
string s1 = “Welcome”;
string s2 = “Welcome”;
if (s1.Equals(s2))
Console.WriteLine(“The strings are the same”);
if (String.Equals(s1,s2))
Console.WriteLine(“The strings are the same”);
Compare Method
The Compare method compares two strings lexically; that is, it compares the strings according to their sort order. The return value from Compare is as follows:
- A negative integer if the first string comes before the second
- 0 if the strings are the same
- A positive integer if the first string comes after the second
string s1 = “Tintinnabulation”;
string s2 = “Velocipede”;
int comp = String.Compare(s1,s2); // Negative return
By definition, any string, including an empty string, compares greater than a null reference, and two null references compare equal to each other. Compare is overloaded. There is a version with three parameters, the third of which is a bool value that specifies whether the case should be ignored in the comparison. The following example shows a case-insensitive comparison:
s1 = “cabbage”;
s2 = “Cabbage”;
comp = String.Compare(s1, s2, true); // Ignore case
Locale-Specific Compare Options
The Compare method has overloaded versions that allow string comparisons based on language-specific sort orders. This can be useful when writing applications for an international market. Further discussion of this feature is beyond the scope of the course. For more information, search for “System.Globalization namespace” and “CultureInfo class” in the .NET ramework SDK Help documents.
String Comparison Operators
The == and != operators are overloaded for the String class. You can use these operators to examine the contents of strings.
string a = “Test”;
string b = “Test”;
if (a == b) … // Returns true
The following operators and methods are equivalent:
- The == operator is equivalent to the String.Equals method.
- The != operator is equivalent to the !String.Equals method.
The other relational operators (<, >, <=, and >=) are not overloaded for the String class.