C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ToCharArrayInfo: Compared to making multiple changes with ToLower and Replace, this approach saves allocations.
ToLowerReplaceTip: This will reduce memory pressure and ultimately improve runtime performance.
C# program that changes characters in string
using System;
class Program
{
static void Main()
{
string input = "The Dev Codes";
/*
*
* 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-purls
Tip: In my testing, using an empty character array and setting its letters one-by-one in the loop yields no performance benefit.
ROT13 MethodNote: This style of method introduces complexity. It is often best to wrap this logic in a helper method, and call that method.