Home
C#
String Change Characters
Updated Nov 13, 2024
Dot Net Perls
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
ROT13
Input and output. Consider the string "aaa 123." We may wish to make 2 separate changes in it at once—change the letter, and the whitespace.
INPUT: aaa 123 OUTPUT: bbb-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.
Info The ToCharArray method will cause an allocation upon the managed heap. Then, the new string constructor will allocate another string.
String ToCharArray
Info Compared to making multiple changes with ToLower and Replace, this approach saves allocations.
String ToLower, ToUpper
String Replace
Tip This will reduce memory pressure and ultimately improve runtime performance.
using System; string input = "aaa 123"; // Change uppercase to lowercase. // Change space to hyphen. // Change a to b. 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 == 'a') { array[i] = 'b'; } } string result = new string(array); Console.WriteLine(result);
bbb-123
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.
String 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 13, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen