简体   繁体   中英

Replacing multiple characters in C#

How would I write a program, using the String.Replace method, that rotates the vowels in a word? Meaning the letter 'a' would be 'e', 'e' would be 'i', 'i' would be 'o', 'o' would be 'u', and finally 'u' would be 'a'.

For example, the word "instructor" would be "onstractur".

Do the following replacements, in order:

y->@ u->y o->u i->o e->i a->e @->a

Of course, @ can be any character that is guaranteed not to occur elsewhere in the string.

Something like myString.Replace("u","~").Replace("o","u").Replace("i","o").Replace("e","i").Replace("a","e").Replace("~","a")

This assumes the string doesn't contain ~ to begin with.

Sorry to post code on a homework question, but some people were saying it couldn't be done with String.Replace , and I wanted to make clear that it could . . . the key is just making sure that no two vowels are simultaneously replaced with the same thing. That is, by the time the o 's become u 's, the u 's must already be something else. Likewise, the u 's can't become a 's until the a 's are replaced with something else. Introducing one additional character ( ~ in my case) seemed like the easiest way to deal with this.

I'm assuming this is homework so I'll give you an explaining answer instead of giving you a proper code solution:

I suggest you first create a list or array of all the vowels. Then you look through your original string and check if each character exists in the list of vowels. If it does, then you replace it by the next item in the vowel list (make sure you wrap around at the end)

Just write a loop and a switch case will solve your problem easily. Is it a homework? What is your effort in trying

Do a replace on each vowel? string.replace . (Do it backwards to prevent wrong replacing)

Backwards will still be a problem without a magic character. See norheim.se answer

y->@ u->y o->u i->o e->i a->e @->a

Perhaps other is going to be angry because I wrote code fur you. But remark is that I am also newbile in programing world and many times I had questions here on SO which is now looks to me trivial.

Maybe and my code is not good but here is how I will try to do that:

using System;
namespace CommandLine{
class Test{

    [STAThread]
    static void Main(string[] Args)
    {
        Console.WriteLine("Enter the word: ");
        string regWord = Console.ReadLine();
        string vowWord = VowelWord(regWord);
        Console.WriteLine("Regural word {0} is now become {1}", regWord, vowWord);
        Console.ReadKey();

    }
    static string VowelWord(string word)
    {
        string VowelWord = string.Empty;
        char replChar;
        foreach (char c in word.ToCharArray())
        {
            switch(c)
            {
                    //'e' would be 'i', 'i' would be 'o', 'o' would be 'u', and finally 'u' would be 'a'.
                case 'a' : replChar = 'e' ;
                    break;
                case 'e': replChar = 'i';
                    break;
                case 'i': replChar = 'o';
                    break;
                case 'o' : replChar = 'u';
                    break;
                case 'u' : replChar = 'a';
                    break;
                default: replChar = c;
                    break;
            }

            VowelWord += replChar;
        }

        return VowelWord;

    }
    }
}

Unfortunately you aren't going to get very far with string.Replace... you'll end up with all vowels being the same (as you are finding out). You need to do all of your replacements in one pass. Your professor gave you a pretty challenging problem, all things considered... especially considering the "no loops" requirements.

You can use String.Replace if you use a placeholder character for one or more characters. It'll make things a little complicated and silly, but I think that's the point of a lot of beginning programming problems.

Since it is homework, I'll try to stick to hints. Do a little research into regular expressions and Regex.Replace. You'll likely find what you are looking for there.

Edit: Just saw you can only use String.Replace. Sorry about that. You'll have to use a placeholder character.

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.

您想要的方法是String.Replace

Sounds a bit like homework.

If you post code showing what you are trying to do and where you are having problems you are more likely to get an answer, as at least it shows you've attempted to find a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM