繁体   English   中英

为字符串索引分配新值

[英]Assign new value to a string index

我需要将用户输入字符串中的字符aeiou转换为指定的符号。 以下是我到目前为止的情况。

作业

首先提示用户输入加密的文本字符串。 验证这不是空白。 将此文本字符串发送到您将创建的将自动解密的自定义方法。 解密后,将此文本字符串返回到main,您将输出加密和解密的字符串。

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

  • @ = a
  • # = e
  • ^ = i
  • * = o
  • + = u

我目前的代码

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循环时,如果字符串在字符串中的任何位置包含@#^* + ,则它将评估为true。 因此,如果您的字符串缺少任何这些符号, 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     
}

有很多不同的方法可以做到这一点。 在循环中进行字符串连接(如@Acex所示)通常不赞成; 它会消除很多“垃圾”,并可能减慢速度。 Stringbuilder类通常是更好的选择。 我的代码使用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保持结果。 在每次结果分配后立即设置一个断点,看看发生了什么。

我没有提供很多评论,逐步完成代码,查找课程并弄清楚我在做什么(毕竟你是学生)。

这真的很简单:

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示例

暂无
暂无

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

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