Modify string contents
This article demonstrates several techniques to produce a string
by modifying an existing string
. All the techniques demonstrated return the result of the modifications as a new string
object. To clearly demonstrate this, the examples all store the result in a new variable. You can then examine both the original string
and the string
resulting from the modification when you run each example.
Note
The C# examples in this article run in the Try.NET inline code runner and playground. Select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.
There are several techniques demonstrated in this article. You can replace existing text. You can search for patterns and replace matching text with other text. You can treat a string as a sequence of characters. You can also use convenience methods that remove white space. You should choose the techniques that most closely match your scenario.
Replace text
The following code creates a new string by replacing existing text with a substitute.
string source = "The mountains are behind the clouds today.";
// Replace one substring with another with String.Replace.
// Only exact matches are supported.
var replacement = source.Replace("mountains", "peaks");
Console.WriteLine($"The source string is <{source}>");
Console.WriteLine($"The updated string is <{replacement}>");
The preceding code demonstrates this immutable property of strings. You can see in the preceding example that the original string, source
, is not modified. The String.Replace method creates a new string
containing the modifications.
The Replace method can replace either strings or single characters. In both cases, every occurrence of the sought text is replaced. The following example replaces all ' ' characters with '_':
string source = "The mountains are behind the clouds today.";
// Replace all occurrences of one char with another.
var replacement = source.Replace(' ', '_');
Console.WriteLine(source);
Console.WriteLine(replacement);
The source string is unchanged, and a new string is returned with the replacement.
Trim white space
You can use the String.Trim, String.TrimStart, and String.TrimEnd methods to remove any leading or trailing white space. The following code shows an example of each. The source string does not change; these methods return a new string with the modified contents.
// Remove trailing and leading white space.
string source = " I'm wider than I need to be. ";
// Store the results in a new string variable.
var trimmedResult = source.Trim();
var trimLeading = source.TrimStart();
var trimTrailing = source.TrimEnd();
Console.WriteLine($"<{source}>");
Console.WriteLine($"<{trimmedResult}>");
Console.WriteLine($"<{trimLeading}>");
Console.WriteLine($"<{trimTrailing}>");
Remove text
You can remove text from a string using the String.Remove method. This method removes a number of characters starting at a specific index. The following example shows how to use String.IndexOffollowed by Remove to remove text from a string:
string source = "Many mountains are behind many clouds today.";
// Remove a substring from the middle of the string.
string toRemove = "many ";
string result = string.Empty;
int i = source.IndexOf(toRemove);
if (i >= 0)
{
result= source.Remove(i, toRemove.Length);
}
Console.WriteLine(source);
Console.WriteLine(result);
Replace matching patterns
You can use regular expressions to replace text matching patterns with new text, possibly defined by a pattern. The following example uses the System.Text.RegularExpressions.Regex class to find a pattern in a source string and replace it with proper capitalization. The Regex.Replace(String, String, MatchEvaluator, RegexOptions) method takes a function that provides the logic of the replacement as one of its arguments. In this example, that function, LocalReplaceMatchCase
is a local functiondeclared inside the sample method. LocalReplaceMatchCase
uses the System.Text.StringBuilder class to build the replacement string with proper capitalization.
Regular expressions are most useful for searching and replacing text that follows a pattern, rather than known text. See How to: search strings for more details. The search pattern, "the\s" searches for the word "the" followed by a white-space character. That part of the pattern ensures that it doesn't match "there" in the source string. For more information on regular expression language elements, see Regular Expression Language - Quick Reference.
string source = "The mountains are still there behind the clouds today.";
// Use Regex.Replace for more flexibility.
// Replace "the" or "The" with "many" or "Many".
// using System.Text.RegularExpressions
string replaceWith = "many ";
source = System.Text.RegularExpressions.Regex.Replace(source, "the\\s", LocalReplaceMatchCase,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
Console.WriteLine(source);
string LocalReplaceMatchCase(System.Text.RegularExpressions.Match matchExpression)
{
// Test whether the match is capitalized
if (Char.IsUpper(matchExpression.Value[0]))
{
// Capitalize the replacement string
System.Text.StringBuilder replacementBuilder = new System.Text.StringBuilder(replaceWith);
replacementBuilder[0] = Char.ToUpper(replacementBuilder[0]);
return replacementBuilder.ToString();
}
else
{
return replaceWith;
}
}
The StringBuilder.ToString method returns an immutable string with the contents in the StringBuilder object.
Modifying individual characters
You can produce a character array from a string, modify the contents of the array, and then create a new string from the modified contents of the array.
The following example shows how to replace a set of characters in a string. First, it uses the ToCharArray() method to create an array of characters. It uses the IndexOf method to find the starting index of the word "fox." The next three characters are replaced with a different word. Finally, a new string is constructed from the updated character array.
string phrase = "The quick brown fox jumps over the fence";
Console.WriteLine(phrase);
char[] phraseAsChars = phrase.ToCharArray();
int animalIndex = phrase.IndexOf("fox");
if (animalIndex != -1)
{
phraseAsChars[animalIndex++] = 'c';
phraseAsChars[animalIndex++] = 'a';
phraseAsChars[animalIndex] = 't';
}
string updatedPhrase = new string(phraseAsChars);
Console.WriteLine(updatedPhrase);
Unsafe modifications to string
Using unsafe code, you can modify a string "in place" after it has been created. Unsafe code bypasses many of the features of .NET designed to minimize certain types of bugs in code. You need to use unsafe code to modify a string in place because the string class is designed as an immutable type. Once it has been created, its value does not change. Unsafe code circumvents this property by accessing and modifying the memory used by a string
without using normal string
methods. The following example is provided for those rare situations where you want to modify a string in-place using unsafe code. The example shows how to use the fixed
keyword. The fixed
keyword prevents the garbage collector (GC) from moving the string object in memory while code accesses the memory using the unsafe pointer. It also demonstrates one possible side effect of unsafe operations on strings that results from the way that the C# compiler stores (interns) strings internally. In general, you shouldn't use this technique unless it is absolutely necessary. You can learn more in the articles on unsafe and fixed. The API reference for Intern includes information on string interning.
unsafe
{
// Compiler will store (intern)
// these strings in same location.
string helloOne = "Hello";
string helloTwo = "Hello";
// Change one string using unsafe code.
fixed (char* p = helloOne)
{
p[0] = 'C';
}
// Both strings have changed.
Console.WriteLine(helloOne);
Console.WriteLine(helloTwo);
}
You can try these samples by looking at the code in our GitHub repository. Or you can download the samples as a zip file.