Strings

Strings are objects of type String which hold a text value.

C# strings can contain any amount of embedded null characters because no null-terminating character exists at their end. The Length property of a string reveals its amount of Char objects, but not its Unicode characters. Text is stored internally as a sequential, read-only Char object collection. The StringInfo object provides Unicode access for a string while the “[ ]” operator provides read-only access to individual characters.

CREATION

Strings are immutable meaning once created, they cannot be altered. Methods and operators which seem to modify strings actually create a new object holding the result. Review the many ways to declare strings below:

// Declare
string messageOne;

// Initialize to null.
string messageTwo = null;

// Initialize as an empty string using the Empty constant
string messageThree = System.String.Empty;

//Initialize with a literal.
string originalPath = "c:\\XYZ\\Visual Studio";

// Initialize with a verbatim literal.
string newPathOne = @"c:\Program Files\Eclipse";

// Using System.String
System.String messageFour = "Hi Universe!";

// Use implicit typing in local variables (in a method body)
var tempO = "It remains a strongly-typed System.String.";

// Use a const string to stop something from holding another string
//value
const string messageFour = "Controlled.";

// Use the String constructor for a string from a char*, char[], or
//sbyte*
char[] letterz = { 'X', 'Y', 'Z' };
string xyz = new string(letterz);

Only employ the new operator in string creation when performing string initialization using an array of char values.

Strings of zero length require the Empty constant value. The literal representation of a zero-length is “ ”. Using Empty instead of null reduces the likelihood of a NullReferenceException. The static IsNullOrEmpty(string) method is recommended for verification of string value before operation.

When embedding escape characters, use regular string literals:

string formcolumnz = "Column One\tColumn Two\tColumn Three";

Verbatim strings offer better readability when the string contains backslashes such as with file locations. Verbatim strings preserve new line characters, so they prove ideal for multi-line strings. Use double quotation marks for embedding quotation marks in a verbatim string.

String operations are optimized in C#, but in larger jobs (e.g., long loops), string operations impact performance. The StringBuilder class provides a string buffer delivering better performance for these heavier tasks. StringBuilder also allows richer access to and manipulation of strings because unlike String, StringBuilder can be changed. Review examples of StringBuilder use below:

System.Text.StringBuilder sTr = new System.Text.StringBuilder("Pears:
the best snack");
sTr[0] = 'B';
System.Console.WriteLine(sTr.ToString());
System.Console.ReadLine();
class STRBuilder
{
	static void Main()
	{
		System.Text.StringBuilder sTR = new
		System.Text.StringBuilder();

		// Make a string of numbers 0 to 10
		for (int i = 0; i < 11; i++)
		{
			sTr.Append(i.ToString());
		}
		System.Console.WriteLine(sTr);
	}
}

Compare strings with the “==” operator:

string x = "hi";
string y = "h";
// Append to y
y += "i";
Console.WriteLine(x == y);
Console.WriteLine((object)x == (object)y);

Perform concatenation with the “+” operator:

string x = "Whoa" + "dude";

METHODS

Review important methods of the String class below:
Name Description
Compare() It compares strings and returns an integer value.
Concat() It concatenates two strings.
Contains() It checks a string for a specified value.
Copy() It creates a duplicate of a specified string.
Equals() It compares two strings and returns a Boolean value.
Trim() It removes extra whitespace at the beginning and end of a string.