C# String Functions and Manipulation


Trim Function

The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use the Trim(). It strips all white spaces from both the start and end of the string.

string Name = ” String Manipulation ” ;
string NewName = Name.Trim();
MessageBox.Show(“[“+ NewName + “]”);


TrimEnd works in much the same way but u are stripping characters which you specify from the end of the string, the below example first strips the space then the n so the output is String Manipulatio.

string Name = ” String Manipulation ” ;
char[] MyChar = {‘ ‘,’n’};
string NewName = Name.TrimEnd(MyChar);
MessageBox.Show(“[“+ NewName + “]”);


TrimStart is the same as TrimEnd apart from it does it to the start of the string.

string Name = ” String Manipulation ” ;
char[] MyChar = {‘ ‘,’S’};
string NewName = Name.TrimStart(MyChar);
MessageBox.Show(“[“+ NewName + “]”);

Find String within string

Ads by TechClicks

This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.

string MainString = “String Manipulation”;
string SearchString = “pul”;
int FirstChr = MainString.IndexOf(SearchString);
MessageBox.Show(“Found at : ” + FirstChr );

Replace string in string

Below is an example of replace a string within a string. It replaces the word Manipulatin with the correct spelling of Manipulation.

string MainString “String Manipulatin”;
string CorrectString = MainString.Replace(“Manipulatin”, “Manipulation”);
MessageBox.Show(“Correct string is : ” + CorrectString);

Strip specified number of characters from string

This example show how you can strip a number of characters from a specified starting point within the string. The first number is the starting point in the string and the second is the amount of chrs to strip.

string MainString = “S1111tring Manipulation”;
string NewString = MainString.Remove(1,4);


Split string with delimiter

The example below shows how to split the string into seperate parts via a specified dilemeter. The results get put into the Split array and called back via Split[0].

string MainString = “String Manipulation”;
string [] Split = MainString.Split(new Char [] {‘ ‘});

Convert to title (proper) case

This is a simple extension method to convert a string to Proper Case or Title Case (ie the first character of each word is made upper case).

public static string ToTitleCase(this string title)


CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;

TextInfo textInfo = cultureInfo.TextInfo;

return textInfo.ToTitleCase(title);


String Concatenation

String concatenation is the act of combining two strings by adding the contents of one string to the end of another. Earlier in this tutorial we considered string operations including using the concatenation operator (+). We used the following example:

string start = “This is a “;

string end = “concatenated string!”;


string concat = start + end;    // concat = “This is a concatenated string!”

The String class also provides a method for concatenating strings. The Concat method allows many strings to be passed as arguments. The strings are joined together and a new, concatenated string is returned:

string start = “This is a “;

string end = “concatenated string!”;


string concat = string.Concat(start, end);

NB: As with previous string functions, the original strings are unchanged.

Inserting Strings into Strings

The String class provides a method that inserts one string into the middle of another. The Insert method acts upon an existing string variable or literal and requires two parameters. The first is an integer that indicates the position where the second string is to be inserted. This integer counts characters from the left with zero indicating that the insertion will be at the beginning of the string. The second parameter is the string to be inserted.

string template = “Please ask for  on arrival.”;

string tutor = “Lisa”;


Console.WriteLine(template.Insert(15, tutor));


// Outputs: “Please ask for Lisa on arrival.”

Removing Characters from a String

The Remove method allows characters to be deleted from a string, shortening the string accordingly. There are two overloads available. The first requires a single parameter to indicate the start position for the character removal. The second overload adds a second parameter specifying how many characters to delete. Any further characters are unaffected.

string sample = “The quick brown fox jumps over the lazy dog.”;


string result = sample.Remove(16);      // result = “The quick brown ”

result = sample.Remove(16, 24);         // result = “The quick brown dog.”


Extracting Text from a String

The String class provides a useful function to extract a piece of text from the middle of a string. This method has two overloads that are very similar to those of the Remove method. However, rather than removing the middle section of the string and keeping the start and end, the Substring method discards the start and end and returns the middle section. The following code illustrates this using the same parameters as the previous example.

string sample = “The quick brown fox jumps over the lazy dog.”;


string result = sample.Substring(16);   // result = “fox jumps over the lazy dog.”

result = sample.Substring(16, 24);      // result = “fox jumps over the lazy ”

Search and Replace

All modern word processors and text editors include a search and replace function that permits a specified piece of text to be substituted with a second string. This functionality is provided by the Replace method. The method accepts two parameters. The first is the string to search for and the second is the string to use as a substitute. When executed, all instances of the first string are automatically replaced.

string sample = “The brown fox.”;


string result = sample.Replace(“brown”, “red”);   // result = “The red fox.”

Copying Strings

The final simple string manipulation function to be considered in this article is the Copy method. This method creates a copy of an existing string. It provides the same functionality as assigning to a string directly.

string sample = “The brown fox.”;


string result = string.Copy(sample);    // result = “The brown fox.”


Equality and Inequality Operators

In an earlier part of the C# Fundamentals tutorial we discussed the equality (==) and inequality (!=) relational operators. These operators allow an exact, case-sensitive comparison of two strings. In the case of the equality operator, if the strings match, the resultant Boolean value is true. If they are different the result is false. The inequality operator returns the opposite result, as shown below:

string s1 = "String to compare.";
string s2 = "String to compare.";
string s3 = "String to Compare.";   // Note the capital 'C'
bool result;

result = s1 == s2;                  // result = true
result = s1 == s3;                  // result = false
result = s1 != s2;                  // result = false
result = s1 != s3;                  // result = true

These operators are useful but have limitations. They do not allow you to consider the equality of two strings that match in all but capitalisation or other cultural factors. Nor do they allow you to determine that one string is greater than another. This article explains the methods that are provided to solve these problems.

Relative Comparison  & CompareTo Method

The .NET framework provides a method named CompareTo for many data types, including strings. It allows two values to be compared and returns a result that indicates not only if they are equal but also which is the greater when they are not. The method considers cultural information when comparing strings. For example, Japanese katakana characters can be written in two ways, half-width or full-width. The CompareTo method considers characters written as full-width to be equal to the same half-width characters. The same cultural information is used to determine which string is the greater.

The CompareTo method operates against an existing string. The string that it is to be compared with is passed to a parameter. The method returns an integer indicating the result of the comparison as follows:

Return Value


    Zero                                   The strings are equal.
Less than Zero                            The first string is less than the second.
More than Zero            The first is greater than the second or the second string is null.

This can be clarified with an example:

string animal1 = "Cat";
string animal2 = "Dog";
int result;

result = animal1.CompareTo("Cat");          // result is zero
result = animal2.CompareTo("Cat");          // result is greater than zero
result = animal1.CompareTo(animal2);        // result is less than zero

NB: As this method is called against an existing string instance, if the string is null an exception occurs:

string animal = null;
int result;

result = animal.CompareTo("Cat");           // Causes an exception


Compare Method

The Compare function is a static method of the string class. It provides similar functionality to CompareTo but allows more options to be specified. As a static member of the string class, both strings are passed as parameters.

string animal1 = "Cat";
string animal2 = "Dog";
int result;

result = String.Compare(animal1, "Cat");    // result is zero
result = String.Compare(animal2, "Cat");    // result is greater than zero
result = String.Compare(animal1, animal2);  // result is less than zero

Null Comparison

The CompareTo method raises an exception if the string that is being tested is null because a null object has no available methods. However, as the Compare method is static, null strings can be compared.

string animal = "Cat";
int result;

result = String.Compare(animal, null);      // result is greater than zero
result = String.Compare(null, animal);      // result is less than zero
result = String.Compare(null, null);        // result is zero

Case Sensitivity

The Compare method allows you to decide whether to perform case-sensitive or case-insensitive comparisons. The differentiation between upper case and lower case lettering is applied according to the user’s language settings. To determine whether to use case-sensitive comparison a third, Boolean parameter is used. If the value is true, character casing is ignored. If false, the effect is the same as not supplying the parameter at all; the test is case-sensitive.

This example assumes UK English settings:

string animal1 = "Cat";
string animal2 = "cat";                             // Note use of lower case
int result;

result = String.Compare(animal1, animal2, true);    // Strings are equal
result = String.Compare(animal1, animal2, false);   // Strings are not equal

The Compare method includes overloaded versions allowing the comparison of strings using further international language settings, as well as options for comparing parts of strings. These are beyond the scope of this tutorial but are worth exploring. More information can be found at the MSDN definition of String.Compare web page.

CompareOrdinal Method

The CompareOrdinal static method allows case-sensitive comparison of two strings. It differs from Compare in that the comparison result is based upon the numeric Unicode values for each character. As the importance of characters in a cultural context can be different to the fixed numeric ordering of Unicode, different results may occur when comparing using this method. This is shown in the following example, which assumes a UK English configuration:

string animal1 = "Cat";
string animal2 = "cat";                             // Note use of lower case
int result;

result = String.Compare(animal1, animal2);      //result is greater than zero
result = String.CompareOrdinal(animal1, animal2); // result is less than zero

Equals Method

The Equals method is included for completeness. It returns a Boolean result indicating if two strings match, similar to the equality operator (==). The method can be used against a string object with a single parameter or as a static member with two parameters for the strings to be compared.

string animal = "Cat";
bool result;

result = animal.Equals("Cat");                      // result = true
result = animal.Equals("cat");                      // result = false
result = String.Equals(animal, "Cat");              // result = true
result = String.Equals(animal, "cat");              // result = false

NET 2.0 IsNullOrEmpty Method

Sometimes it is necessary to check if a string is either empty or is undefined (null). Using .NET 1.1, this would require two tests. The .NET framework 2.0 introduces a new static method, named IsNullOrEmpty, which performs both tests with one statement. The method returns true when the string is empty or null.

string animal1 = "Cat";
string animal2 = "";
string animal3 = null;
bool result;

result = String.IsNullOrEmpty(animal1);             // result = false
result = String.IsNullOrEmpty(animal2);             // result = true
result = String.IsNullOrEmpty(animal3);             // result = true

Retrieving a String’s Length

It is often necessary to check the length of a string, particularly to validate a user’s input. The String class provides a property named Length that gives us this information. The property returns an integer representing the number of characters present.

string animal = "Dog";
int result;

result = animal.Length;                     // result is 3
result = "Elephant".Length;                 // result is 8

NB: The Length property is efficient to execute. When checking if a string is empty, it is more efficient to check for zero length than to compare the string value to String.Empty or “”.

Locating Text Within a String

In an earlier article we examined the Substring method, which allows the extraction of characters from a specified position in a string. The reverse of this is to specify a series of characters and identify the position at which that sub-string appears within a string. This can be achieved with the IndexOf and LastIndexOf methods.

IndexOf takes a parameter containing a string to search for. If this exists within the main string the position of the first occurrence is returned. This position is known as the index and is an integer indicating the number of characters between the start of the string and the found text. If the search term appears at the start of the string the index is zero. Should the sub-string not exist within the main string the method returns -1.

LastIndexOf is similar to IndexOf. However, instead of returning the index of the first occurrence of the search term, LastIndexOf returns the position of the last occurrence.

string phrase = "The quick brown fox jumps over the lazy dog.";
int result;

result = phrase.IndexOf("brown");           // result is 10
result = phrase.LastIndexOf("dog");         // result is 40
result = phrase.IndexOf("green");           // result is -1
result = phrase.LastIndexOf("blue");        // result is -1

Specifying a Limited Search

IndexOf and LastIndexOf can be limited further by specifying a start position for the search. With IndexOf only occurrences of the specified sub-string at or to the right of this position are found. When using LastIndexOf, only matching sub-strings to the left of this position are located.

string phrase = "The quick brown fox jumps over the lazy dog.";
int result;

result = phrase.IndexOf("he");              // result is 1
result = phrase.IndexOf("he", 1);           // result is 1
result = phrase.IndexOf("he", 2);           // result is 32
result = phrase.LastIndexOf("he");          // result is 32
result = phrase.LastIndexOf("he",33);       // result is 32
result = phrase.LastIndexOf("he",32);       // result is 1

The search can be limited further with a third parameter. This parameter is an integer that indicates the maximum number of characters that may be examined. If a match does not exist within the range of characters the result returned is -1.

string phrase = "The quick brown fox jumps over the lazy dog.";
int result;

result = phrase.IndexOf("brown");           // result is 10
result = phrase.IndexOf("brown", 5, 4);     // result is -1
result = phrase.LastIndexOf("fox");         // result is 16
result = phrase.LastIndexOf("he", 25, 5);   // result is -1

Simple Container Tests

IndexOf and LastIndexOf are useful when determining the exact position of search terms within strings. However, sometimes it is enough to simply know that a sub-string exists. The String class provides several methods to perform this test.

StartsWith and EndsWith

StartsWith and EndsWith allow you to determine if a string starts or ends with a specific series of characters. Both methods accept an argument containing the string to match and return a Boolean value indicating the result. These methods are case-sensitive.

string phrase = "The quick brown fox jumps over the lazy dog.";
bool result;

result = phrase.StartsWith("The quick");    // result is true
result = phrase.StartsWith("lazy dog.");    // result is false
result = phrase.EndsWith("lazy dog.");      // result is true
result = phrase.EndsWith("The quick");      // result is false

.NET 2.0 Contains Method

The final string function considered in this article is Contains. Introduced in version 2.0 of the .NET framework, it operates in a similar manner to StartsWith and EndsWith but checks if the specified search term exists at any position within the main string.

string phrase = "The quick brown fox jumps over the lazy dog.";
bool result;

result = phrase.Contains("brown fox");      // result is true
result = phrase.Contains("lazy fox.");      // result is false



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s