You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET窗体文本框预定义密码替换失效,标签显示原输入问题

问题:.NET窗体中替换加密功能未生效,标签仅显示原文本

我尝试在.NET窗体中,将文本框输入的字符串通过预定义密码表进行替换加密,但功能未生效。调试时标签仅显示输入的原文本,以下是我的代码:

public string Encode(string input)
{
    int counter = 0;
    string output = "";
    List<string> inputlist = new List<string> { "a", "b", "c", "d", "e", "f", "g", "h",
    "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
    List<string> cipherlist = new List<string> { "r","s","n","e","p","h","c","a","t","i","m","g","l",
    "x","w","v","f","u","j","z","k","o","b","y","d","q"};
    do
    {
        output = input.Replace(inputlist[counter], cipherlist[counter]);
        counter++;
    } while (counter < 26);
    return output;
}
private void btnConvert_Click(object sender, EventArgs e)
{
    label1.Text = Encode(textBox1.Text);
}

问题原因

你的加密逻辑存在核心错误:在do-while循环中,每次执行output = input.Replace(...)时,始终用原始的input字符串进行替换,而不是基于上一次替换后的output继续处理。这就导致最后一次循环(counter=25)只会替换input中的"z"为"q",之前的所有替换操作都被覆盖了,最终输出的结果要么是只替换了"z"的原字符串,要么就是完全没变化(如果输入里没有"z")。


修复方案

方案一:优化为字典映射+StringBuilder(推荐)

用字典存储字符映射关系更直观高效,同时使用StringBuilder处理字符串拼接,避免频繁创建字符串对象:

public string Encode(string input)
{
    Dictionary<char, char> cipherMap = new Dictionary<char, char>
    {
        {'a','r'}, {'b','s'}, {'c','n'}, {'d','e'}, {'e','p'}, {'f','h'}, {'g','c'}, {'h','a'},
        {'i','t'}, {'j','i'}, {'k','m'}, {'l','g'}, {'m','l'}, {'n','x'}, {'o','w'}, {'p','v'},
        {'q','f'}, {'r','u'}, {'s','j'}, {'t','z'}, {'u','k'}, {'v','o'}, {'w','b'}, {'x','y'},
        {'y','d'}, {'z','q'}
    };

    StringBuilder output = new StringBuilder();
    foreach (char c in input)
    {
        // 只替换小写字母,其他字符保持原样
        if (cipherMap.ContainsKey(c))
        {
            output.Append(cipherMap[c]);
        }
        else
        {
            output.Append(c);
        }
    }
    return output.ToString();
}

方案二:修复原有列表逻辑

如果想保留原有的列表实现方式,只需将output初始值设为输入字符串,每次替换基于上一次的结果迭代:

public string Encode(string input)
{
    int counter = 0;
    string output = input; // 初始化为输入字符串,后续基于此迭代替换
    List<string> inputlist = new List<string> { "a", "b", "c", "d", "e", "f", "g", "h",
    "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
    List<string> cipherlist = new List<string> { "r","s","n","e","p","h","c","a","t","i","m","g","l",
    "x","w","v","f","u","j","z","k","o","b","y","d","q"};
    do
    {
        output = output.Replace(inputlist[counter], cipherlist[counter]);
        counter++;
    } while (counter < 26);
    return output;
}

额外说明

  • 若需要支持大写字母,可以添加对应的字典映射,或者先将输入字符串转为小写处理后再还原大小写。
  • StringBuilder在处理较长文本时,性能远优于反复使用string.Replace拼接字符串。

内容的提问来源于stack exchange,提问作者zalithorn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:30:16