
You want to change the characters in a string in your C# program. Because strings are immutable in this language, you must first convert them to arrays, which can then be changed in memory before conversion back to a string.
This C# tutorial shows how to change many characters in a string at once.
This example shows how you can use a series of if-statements to change characters in a string. You can make many mutations in a single pass through the string. This can improve performance and also make certain transformations possible. For the example, we make three changes: we lowercase characters, and we change the values of spaces and one letter.
Program that changes characters in string [C#]
using System;
class Program
{
static void Main()
{
string input = "Dot Net Perls";
/*
*
* 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);
}
}
Output
dot-nut-purlsAllocations. In this program, the ToCharArray method will cause an allocation upon the managed heap. Then, the new string constructor will allocate another string. Compared to making multiple changes with ToLower and Replace, this approach saves allocations, which will reduce memory pressure and ultimately improve runtime performance.
ToCharArray Method, Convert String to Array ToLower Method Replace String ExamplesAdditionally, some transformations are simply not possible using standard string methods. For example using ROT13 encoding is best done with the ToCharArray and new string constructor style of code as shown here. In my testing, using an empty character array and setting its letters one-by-one in the loop (without ToCharArray) yields no performance benefit.
ROT13
If you need to change one letter at a certain position (such as the first letter), this approach to string mutation is also ideal. You can call ToCharArray, then set array[0] to the new letter, and then use the new string constructor.
Uppercase First Letter String ConstructorTo change characters 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 directly. Because of the additional complexity involved, it is often best to wrap these method calls in a helper method, and call that method where needed.
String Type