BlackWasp
C# Programming
.NET 1.1

C# String Testing Functions

The twenty-fourth part of the C# Fundamentals tutorial completes the initial examination of the string manipulation functionality provided by the String class. This article investigates methods available for testing the contents of strings.

Retrieving a String's Length

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

string animal = "Dog";
int result;

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

NB: The Length property is a very efficient method to execute. For this reason, when checking if a string is empty, it is more efficient to compare the length of the string with zero than to compare the string value itself to String.Empty or "".

Locating Text Within a String

In an earlier article in the C# Fundamentals tutorial we examined the use of the Substring method that allows the extraction of a number of characters from a specified position in a string. The reverse of this functionality 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.

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

The LastIndexOf method operates in a similar manner to IndexOf. However, instead of returning the index of the first occurrence of the search term, LastIndexOf returns the position of the last occurrence. This is still an index value counted from the left of the string.

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

The IndexOf and LastIndexOf methods can be limited further by specifying the start position from which to search. In the case of the IndexOf method only occurrences of the specified sub-string at or to the right of this position will be matched. 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 value that indicates the maximum number of characters from the start position that may be examined. If a match does not exist within the range of characters then the result returned is the same as if no match exists at all, -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

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

StartsWith and EndsWith

The StartsWith and EndsWith methods allow the developer to determine if a string starts or ends with a specific series of characters. Both methods accept a single parameter for the sub-string to match, and both 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 to consider in this article is the Contains method. Microsoft introduced this method 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
Link to this Page11 December 2006
RSS RSS Feed