Home > Articles

  • Print
  • + Share This
This chapter is from the book

3.6. Working with Substrings

You need to change or extract a specific portion of a string.

Technique

To copy a portion of a string into a new string, use the SubString method within the System.String class. You call this method using the string object instance of the source string:

string source = "ABCD1234WXYZ";
string dest = source.Substring( 4, 4 );
Console.WriteLine( "{0}\n", dest );

To copy a substring into an already existing character array, use the CopyTo method. To assign a character array to an existing string object, create a new instance of the string using the new keyword, passing the character array as a parameter to the string constructor as shown in the following code, whose ouput appears in Figure 3.2:

string source = "ABCD";
char [] dest = { '1', '2', '3', '4', '5', '6', '7', '8' };

Console.Write( "Char array before = " );
Console.WriteLine( dest );

// copy substring into char array
source.CopyTo( 0, dest, 4, source.Length );

Console.Write( "Char array after = " );
Console.WriteLine( dest );

// copy back into source string
source = new String( dest );

Console.WriteLine( "New source = {0}\n", source ); 

Figure 3.2Figure 3.2 Use the CopyTo method to copy a substring into an existing character array.

If you need to remove a substring within a string and replace it with a different substring, use the Replace method. This method accepts two parameters, the substring to replace and the string to replace it with:

string replaceStr = "1234";
string dest = "ABCDEFGHWXYZ";

dest = dest.Replace( "EFGH", replaceStr );

Console.WriteLine( dest );

To extract an array of substrings that are separated from each other by one or more delimiters, use the Split method. This method uses a character array of delimiter characters and returns a string array of each substring within the original string as shown in the following code, whose output appears in Figure 3.3. You can optionally supply an integer specifying the maximum number of substrings to split:

char delim = '\\';
string filePath = "C:\\Windows\\Temp";
string [] directories = null;

directories = filePath.Split( delim );
        
foreach (string directory in directories) 
{
  Console.WriteLine("{0}", directory);
}

Figure 3.3Figure 3.3 You can use the Split method in the System.String class to place delimited substrings into a string array.

Comments

Parsing strings is not for the faint of heart. However, the job becomes easier if you have a rich set of methods that allow you to perform all types of operations on strings. Substrings are the goal of a majority of these operations, and the string class within the .NET Framework contains many methods that are designed to extract or change just a portion of a string.

The Substring method extracts a portion of a string and places it into a new string object. You have two options with this method. If you pass a single integer, the Substring method extracts the substring that starts at that index and continues until it reaches the end of the string. One thing to keep in mind is that C# array indices are 0 based. The first character within the string will have an index of 0. The second Substring method accepts an additional parameter that denotes the ending index. It lets you extract parts of a string in the middle of the string.

You can create a new character array from a string by using the ToCharArray method of the string class. Furthermore, you can extract a substring from the string and place it into a character array by using the CopyTo method. The difference between these two methods is that the character array used with the CopyTo method must be an already instantiated array. Whereas the ToCharArray returns a new character array, the CopyTo method expects an existing character array as a parameter to the method. Furthermore, although methods exist to extract character arrays from a string, there is no instance method available to assign a character array to a string. To do this, you must create a new string object using the new keyword, as opposed to creating the familiar value-type string, and pass the character array as a parameter to the string constructor.

Using the Replace method is a powerful way to alter the contents of a string. This method allows you to search all instances of a specified substring within a string and replace those with a different substring. Additionally, the length of the substring you want to replace does not have to be the same length of the string you are replacing it with. If you recall the number of times you have performed a search and replace in any application, you can see the possible advantages of this method.

One other powerful method is Split. By passing a character array consisting of delimiter characters, you can split a string into a group of substrings and place them into a string array. By passing an additional integer parameter, you can also control how many substrings to extract from the source string. Referring to the code example earlier demonstrating the Split method, you can split a string representing a directory path into individual directory names by passing the \ character as the delimiter. You are not, however, confined to using a single delimiter. If you pass a character array consisting of several delimiters, the Split method extracts substrings based on any of the delimiters that it encounters.

  • + Share This
  • 🔖 Save To Your Account