If you want to extract a part of a string, you can use the Substring() method. The Substring() method accepts two arguments, the start index and the length of the string to extract. The following program shows you this.

string str1 = "This is a sample string.";
//Extract sample
string str2 = str1.Substring(10, 6);

Console.WriteLine("str1 = {0}", str1);
Console.WriteLine("str2 = {0}", str2);
str1 = This is a sample string.
str2 = sample

We started the extraction at index 10. You can see that “sample” starts at index 10 (11th character). The length will determine how many characters will be extracted. Since we provided six as the length, 6 characters was extracted including the character at the start index. If you don’t want to count manually the position of the “sample”, you can use the IndexOf method.

string str2 = str1.Substring(str1.IndexOf("sample"), 6);

Another overload of the Substring method accepts only one argument which is the start index. It starts the extraction from the start index until the end of the string.

Removing Strings


To remove strings, you can use the Remove method. It’s parameters are the same as the Substring method.

string str1 = "This is a sample string.";
Console.WriteLine(str1);
Console.WriteLine("Removing "sample"...");
str1 = str1.Remove(10, 7);
Console.WriteLine(str1);
This is a sample string.
Removing "sample "...
This is a string.

Another overload of the Remove method accepts one argument which is the start index. Everything will be removed from the start index to the end of the string.

Replacing Strings


You can use the Replace method to replace all occurrences of a string with another string. For example, you can change all occurrences of “dog” with “cat”.

string str1 = "That dog is a lovely dog.";
Console.WriteLine(str1);
Console.WriteLine("Replacing all dogs with cats...");
str1 = str1.Replace("dog", "cat");
Console.WriteLine(str1);
That dog is a lovely dog.
Replacing all dogs with cats...
That cat is a lovely cat.

The Replace method accepts two arguments. The first one is the string to be replaced and the second one is the replacement string. The Replace method searches for all occurrences of the word “dog” then replaced it with the word “cat”.

You can also use the Replace method to remove all occurrences of a string.

string str1 = "That dog is a lovely dog.";
Console.WriteLine(str1);
Console.WriteLine("Removing all dogs...");
str1 = str1.Replace("dog", String.Empty);
Console.WriteLine(str1);
That dog is a lovely dog.
Removing the dogs...
That is a lovely .

The code above uses String.Empty as the replacement string. String.Empty is equal to “” which means empty string. So every occurrence of the string being replace was emptied thus removing them from the actual string.