简体   繁体   English

在C#中替换多个字符

[英]Replacing multiple characters in C#

How would I write a program, using the String.Replace method, that rotates the vowels in a word? 我将如何使用String.Replace方法编写一个程序来旋转元音? 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'. 意味着字母“ a”将是“ e”,“ e”将是“ i”,“ i”将是“ o”,“ o”将是“ u”,最后“ u”将是“ a”。

For example, the word "instructor" would be "onstractur". 例如,单词“ instructor”将是“ onstractur”。

Do the following replacements, in order: 按顺序执行以下替换:

y->@ u->y o->u i->o e->i a->e @->a 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") 类似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 . 很抱歉在家庭作业问题上张贴代码,但有人说String.Replace无法完成,我想澄清一下。 . . 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. 也就是说,当o变成uu必须已经是别的东西。 Likewise, the u 's can't become a 's until the a 's are replaced with something else. 同样,除非将a替换为其他内容,否则u不能成为a 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 . string.replace (Do it backwards to prevent wrong replacing) (向后进行以防止错误更换)

Backwards will still be a problem without a magic character. 如果没有魔术角色,向后移动仍然是一个问题。 See norheim.se answer 参见norheim.se答案

y->@ u->y o->u i->o e->i a->e @->a 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. 但是要说的是,我在编程领域也很新手,而且我在这里有很多关于SO的问题,现在我觉得这很微不足道。

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). 不幸的是,使用string并不会走的太远。替换...最终所有元音都一样(最终发现)。 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. 如果对一个或多个字符使用占位符,则可以使用String.Replace。 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. 对正则表达式和Regex.Replace做一些研究。 You'll likely find what you are looking for there. 您可能会在这里找到想要的东西。

Edit: Just saw you can only use String.Replace. 编辑:刚看到您只能使用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. 请注意, str.Replace不会更改字符串。 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: 实际上,编写以下行无济于事,因为Replace的结果未保存在任何地方:

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. 注意(i + 1) % cycle.Length是循环数组的常见技巧- %代表mod运算符,因此这使我可以在数组中的正确位置。

您想要的方法是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. 如果您发布的代码显示了您正在尝试做的事情以及您在哪里遇到问题,则更有可能获得答案,因为至少它表明您已经在尝试找到解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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