Change Characters in StringModify many characters in a string at once using ToCharArray and a for-loop.
This page was last reviewed on Jun 30, 2021.
Change characters. In C# programs, strings are immutable. If we want to change their characters, we must first convert them to arrays.
C# performance. A char array can be changed in memory before conversion back to a string. This is efficient. We show how to change string characters in this way.
Char Array
Input and output. Consider the string "eee 123." We may wish to make 2 separate changes in it at once—change the letter, and the whitespace.
Required output:
INPUT: eee 123 OUTPUT: uuu-123
Example code. We use a series of if-statements to change characters in a string. You can make many mutations in a single pass through the string.
Next We make 3 changes: we lowercase characters, and we change the values of spaces and one letter.
ToCharArray This method will cause an allocation upon the managed heap. Then, the new string constructor will allocate another string.
Info Compared to making multiple changes with ToLower and Replace, this approach saves allocations.
Tip This will reduce memory pressure and ultimately improve runtime performance.
using System; class Program { static void Main() { string input = "eee 123"; // Change uppercase to lowercase. // Change space to hyphen. // Change e to u. char[] array = input.ToCharArray(); for (int i = 0; i < array.Length; i++) { char let = array[i]; if (char.IsUpper(let)) { array[i] = char.ToLower(let); } else if (let == ' ') { array[i] = '-'; } else if (let == 'e') { array[i] = 'u'; } } string result = new string(array); Console.WriteLine(result); } }
ROT13. Some transformations are not possible using standard string methods. ROT13 encoding is best done with the ToCharArray and new string constructor style of code.
One letter. If you need to change one letter at a certain position (such as the first letter), this approach to string mutation is also ideal.
Uppercase First Letter
String Constructor
Summary. To change chars in a string, you must use a lower-level representation of the character data, which you can acquire with ToCharArray. You cannot simply assign indexes in a string.
Summary, continued. This style of method introduces complexity. It is often best to wrap this logic in a helper method, and call that method.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 30, 2021 (image).
© 2007-2022 Sam Allen.