如何在 C# 中将文本中的字符替换为另一个字符

本文关键字:字符 替换 另一个 文本 | 更新日期: 2023-09-27 17:56:02

如果有人能帮忙,我将不胜感激!我需要将文本中的每个字符(加密,我从文件中读取)替换为字典中的另一个字符。

 StreamReader st = new StreamReader(@"C:'path of text");
 string text = st.ReadToEnd();
 st.Close();
 char[] textChar = text.ToCharArray();  //splitting text into characters

所以,在我的字典Dictionary<char, char> keys = new Dictionary<char,char>();键中,我有一些字母,说"n"和值 - 另一个字母,说"a"。所以我需要在我的文本中用"a"替换每个"n"。字典分别有 26 个字母表示键和 26 个字母表示值。

现在我尝试替换字母并将"解密"文本写入某个文件

StreamWriter sw = new StreamWriter(@"path for decrypted file");
 foreach(KeyValuePair<char, char> c in keys)
 {
    for(int i =0; i< textChar.Length; i++)
    {
         if (textChar.Contains(c.Key))
         {  //if text has char as a Key in Dictionary
             textChar[i] = keys[c.Key]; //replace with its value
         }
         else 
         {
             sw.Write(textChar[i]);  //if not, just write (in case of punctuatuons in text which i dont want to replace)
         }
     }
  }
  st.Close();
  file.Close();

此代码无法正常工作,因为替换错误。我将不胜感激任何帮助!

如何在 C# 中将文本中的字符替换为另一个字符

尝试类似的代码,我在没有Visual Studio的情况下编写了它,所以也许它需要一些更正:)

string text = File.ReadAllText(@"path for decrypted file");
foreach(var key in keys)
{
  text = text.Replace(key.Key, key.Value);
}

试试这个:

StreamReader st = new StreamReader(@"C:'path of text");
string text = st.ReadToEnd();
st.Close();
foreach(KeyValuePair<char, char> c in keys)
{
    text = text.Replace(c.Key, c.Value);
}

String.Replace 返回一个新字符串,其中此实例中指定 Unicode 字符的所有匹配项都将替换为另一个指定的 Unicode 字符。

你为什么使用char[] textChar?在大多数情况下,最好使用string

你的代码有问题...

例如,如果您有一个键(a,z)和一个键(z,b),会发生什么情况。如果你只是应用一个直接的交换,你所有的a都会变成z,然后你所有的z都会变成b。(这意味着所有你是 a 和 z 都变成了 b)。

您需要将项目转换为某个中间值,然后可以根据需要进行解码。

(a,z)
(z,b)

编码

(a,[26])
(z,[02])

解码

([26],z)
([02],b)