C# - Strings


A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0'). The Length property of a string represents the number of Char objects it contains, not the number of Unicode characters. To access the individual Unicode code points in a string, use the StringInfo object.

string vs. System.String

In C#, the string keyword is an alias for String. Therefore, String and string are equivalent, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings. In addition, the C# language overloads some operators to simplify common string operations

C# string function

String FunctionsDefinitions
Clone()Make clone of string.
CompareTo()Compare two strings and returns integer value as output. It returns 0 for true and 1 for false.
Contains()The C# Contains method checks whether specified character or string is exists or not in the string value.
EndsWith()This EndsWith Method checks whether specified character is the last character of string or not.
Equals()The Equals Method in C# compares two string and returns Boolean value as output.
GetHashCode()This method returns HashValue of specified string.
GetType()It returns the System.Type of current instance.
GetTypeCode()It returns the Stystem.TypeCode for class System.String.
IndexOf()Returns the index position of first occurrence of specified character.
ToLower()Converts String into lower case based on rules of the current culture.
ToUpper()Converts String into Upper case based on rules of the current culture.
Insert()Insert the string or character in the string at the specified position.
IsNormalized()This method checks whether this string is in Unicode normalization form C.
LastIndexOf()Returns the index position of last occurrence of specified character.
LengthIt is a string property that returns length of string.
Remove()This method deletes all the characters from beginning to specified index position.
Replace()This method replaces the character.
Split()This method splits the string based on specified value.
StartsWith()It checks whether the first character of string is same as specified character.
Substring()This method returns substring.
ToCharArray()Converts string into char array.
Trim()It removes extra whitespaces from beginning and ending of string.

Constructing strings

The simplest way to construct a string is to assign a literal

string s1 = "Hello";

To create a repeating sequence of characters you can use string’s constructor:

Console.Write (new string ('*', 10)); // **********

You can also construct a string from a char array. The ToCharArray method does the reverse:

char[] ca = "Hello".ToCharArray();
string s = new string (ca); // s = "Hello"

Null and empty strings

An empty string has a length of zero. To create an empty string, you can use either a literal or the static string.Empty field; to test for an empty string, you can either perform an equality comparison or test its Length property:

string empty = "";
Console.WriteLine (empty == ""); // True
Console.WriteLine (empty == string.Empty); // True
Console.WriteLine (empty.Length == 0); // True

Because strings are reference types, they can also be null:

string nullString = null;
Console.WriteLine (nullString == null); // True
Console.WriteLine (nullString == ""); // False
Console.WriteLine (nullString.Length == 0); // NullReferenceException

The static string.IsNullOrEmpty method is a useful shortcut for testing whether a given string is either null or empty

Accessing characters within a string

A string’s indexer returns a single character at the given index. As with all functions that operate on strings, this is zero-indexed:

string str = "abcde";
char letter = str[1]; // letter == 'b'

string also implements IEnumerable, so you can foreach over its characters:

foreach (char c in "123") 
            Console.Write (c + ","); // 1,2,3,

Searching within strings

The simplest methods for searching within strings are Contains, StartsWith, and EndsWith. These all return true or false:

Console.WriteLine ("quick brown fox".Contains ("brown")); // True
Console.WriteLine ("quick brown fox".EndsWith ("fox")); // True

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...";
    position = str1.IndexOf("long", ++position);
    if (position > 0)
} while (position > 0);

This prints out the following:


Splitting and joining strings

Split takes a sentence and returns an array of words:

string[] words = "The quick brown fox".Split();
foreach (string word in words)
Console.Write (word + "|"); // The|quick|brown|fox|

By default, Split uses whitespace characters as delimiters; it’s also overloaded to accept a params array of char or string delimiters.

The static Join method does the reverse of Split. It requires a delimiter and string array:

string[] words = "The quick brown fox".Split();
string together = string.Join (" ", words); // The quick brown fox

String.Format and composite format strings

The static Format method provides a convenient way to build strings that embed variables. The embedded variables can be of any type; the Format simply calls ToString on them.

The master string that includes the embedded variables is called a composite format string. When calling String.Format, you provide a composite format string followed by each of the embedded variables. For example:

string composite = "It's {0} degrees in {1} on this {2} morning";
string s = string.Format (composite, 35, "Perth", DateTime.Now.DayOfWeek);