string str = "instructor";
Note that str.Replace
doesn't change the string. Rather, it returns a new string, with the replaced characters.
In effect, writing the following line does nothing, because the result of Replace isn't saved anywhere:
str.Replace('a', 'e');
To keep the new result you need a variable that point to it:
string result;
result = str.Replace('a', 'e');
Or, you can reuse the same variable:
str = str.Replace('a', 'e');
Now, this can be done in a single line, but I wouldn't submit that as homework... A clearer solution, using a temp character, might be:
string str = "instructor";
char placeholder = '\u2609'; // same as '☉'
string result = str; //init value is same as str
result = result.Replace('u', placeholder);
result = result.Replace('o', 'u');
// ...
result = result.Replace(placeholder, 'a');
Console.WriteLine(result);
A more general solution might be to use an array to cycle the characters. Here, where using an array to hold all characters:
string str = "instructor";
string result = str; //init value is same as str
char[] cycle = new char[] { '\u2609', 'u', 'o', 'i', 'e', 'a' };
for (int i = 0; i < cycle.Length; i++)
{
int nextPosition = (i + 1) % cycle.Length;
result = result.Replace(cycle[nextPosition], cycle[i]);
}
Console.WriteLine(result);
The advantage of this is that it can easily be expanded to other characters, and avoid some repetition. Note that (i + 1) % cycle.Length
is a common trick to cycle an array - %
represents the mod
operator, so this keeps me in the array, in the right position.