为字符串索引分配新值

Assign new value to a string index

我需要将用户输入字符串中的字符aeiou转换为指定的符号。以下是我目前所拥有的。

学校作业

首先提示用户输入加密的文本字符串。验证这不是留空。将此文本字符串发送到您将创建的将对其进行解密的自定义方法中。解密后,return将此文本字符串发送到主目录,您将在其中输出加密和解密的字符串。

要破译文本字符串,您必须执行以下字符替换:

我现在的代码

public static string Decipher (string code)
{
    char[] array = code.ToCharArray();

    for (int i = 0; i < code.Length; i++)
    {
        if (code.Contains("@") && code.Contains("#") && code.Contains("^") &&
            code.Contains("*") && code.Contains("+"))
        {

        }
    }

每次执行此 for 循环时,如果字符串包含 @#^* ,它将评估为真and + 字符串中的任意位置。因此,如果您的字符串缺少这些符号中的任何一个,您的 if 语句将计算为 false 并且什么也不会发生。

幸运的是,您可以很容易地简化它。一种方法是将 string 转换为 char[] 数组并将逻辑分解为多个 if-else 语句,或单个 switch语句,例如:

public static string Decipher (string code)
{
    char[] codeArray = code.ToCharArray(); // convert your code string to a char[] array

    for (int i = 0; i < codeArray.Length; i++)
    {
        switch (codeArray[i]) // Get the char at position i in the array
        {
            case '@': // if the character at i is '@'
                codeArray[i] = 'a'; // Change the character at i to 'a'
                break; // break out of the switch statement - we don't need to evaluate anything else
            case '#': // if the character at i is '#'
                codeArray[i] = 'e'; // Change the character at i to 'e'
                break; // break out of the switch statement - we don't need to evaluate anything else
            // repeat for everything else you need to replace!
        }  
    }
    return new String(codeArray); // Once you're all done, create a string from your deciphered array and return it     
}

真的很简单:

public static string Decipher(string code)
{
    var map = new Dictionary<char, char>()
    {
        { '@', 'a' },
        { '#', 'e' },
        { '^', 'i' },
        { '*', 'o' },
        { '+', 'u' },
    };

    char[] array = code.ToCharArray();

    array = array.Select(x => map.ContainsKey(x) ? map[x] : x).ToArray();

    return new string(array);
}

现在您可以这样做了:

string cipher = "*+tp+t";
string plain = Decipher(cipher);
Console.WriteLine(cipher);
Console.WriteLine(plain);

这输出:

*+tp+t
output

为了备选

以及何时允许您使用现有方法。

你可以这样写:

private Dictionary<char, char> mapping = new Dictionary<char, char>()
{
    { '@', 'a' },
    { '#', 'e' },
    { '^', 'i' },
    { '*', 'o' },
    { '+', 'u' },
};

private string Decrypt(string encryptedString) =>
    string.Concat(encryptedString.Select(s => mapping.ContainsKey(s) ? mapping[s] : s));

和用法:

string result = Decrypt(encryptedString);

参考资料:DotNetFiddle Example

有很多不同的方法可以做到这一点。通常不赞成在循环中进行字符串连接(如@Acex 所示);它旋转出很多 "garbage" 并且可以减慢速度。 Stringbuilder class 通常是更好的选择。我的代码使用 Stringbuilders(好吧,一遍又一遍地使用相同的代码 - 我在两者之间清除它)。

这里有几种方法可以做同样的事情:

const string encoded = "H#ll*, H*w @r# y*+?";

//good old fashioned C-style/brute force:
var buf = new StringBuilder();
foreach (var c in encoded){
    switch(c){
        case '@':
            buf.Append('a');
            break;
        case '#':
            buf.Append('e');
            break;
        case '^':
            buf.Append('i');
            break;
        case '*':
            buf.Append('o');
            break;
        case '+':
            buf.Append('u');
            break;
        default:
            buf.Append(c);
            break;
    }
}
var result = buf.ToString();

//using a lookup table (easily extensible)
buf.Clear();

var decodeDict = new Dictionary<char, char>{
    {'@', 'a'},
    {'#', 'e'},
    {'^', 'i'},
    {'*', 'o'},
    {'+', 'u'},
};

foreach (var c in encoded){
    if (decodeDict.Keys.Contains(c)){
        buf.Append(decodeDict[c]);
    } else {
        buf.Append(c);
    }
}
result = buf.ToString();

//something completely different
//instead of iterating through the string, iterate through the decoding dictionary
buf.Clear();
var working = new StringBuilder(encoded.Length);
working.Append(encoded);
foreach (var pair in decodeDict){
    working.Replace(pair.Key, pair.Value);
}
result = working.ToString();

在每种情况下,result 都包含结果。在每个结果分配后立即放置一个断点,看看发生了什么。

我不会提供很多评论,单步执行代码,查找 classes 并弄清楚我在做什么(毕竟你是学生)。