替换文件c#中的符号
本文关键字:符号 文件 替换 | 更新日期: 2023-09-27 18:24:32
嘿,我正试图替换文件中的一些符号。我做了字典并且我可以在我输入的字符串中替换它。如何读取我的文件,做我的替换并保存到另一个?
class Program
{
static void Main(string[] args)
{
Translit translit = new Translit();
StreamReader sr = new StreamReader("test.txt");
string testIn = "iconb "; //a test input string
string testOut = translit.TranslitFileName(testIn);
Console.WriteLine("Inputed ''{0}''", testIn);
Console.WriteLine("after ''{0}''", testOut);
Console.ReadLine();
}
public class Translit
{
Dictionary<string, string> dictionaryChar = new Dictionary<string, string>()
{
{"а","a"},
{"е","e"},
{"о","o"},
{"р","p"},
{"с","c"}
};
public string TranslitFileName(string source)
{
var result = "";
//symbols for replace
foreach (var ch in source)
{
var ss = "";
//compare dictionary keys
if (dictionaryChar.TryGetValue(ch.ToString(), out ss))
{
result += ss;
}
else result += ch;
}
return result;
}
}
}
试着这样做:
Func<string, string> map = new []
{
new { input = 'a', output = 'x' },
new { input = 'e', output = 'x' },
new { input = 'o', output = 'x' },
new { input = 'p', output = 'x' },
new { input = 'c', output = 'x' },
}
.Select(x => (Func<string, string>)(s => s.Replace(x.input, x.output)))
.Aggregate((f0, f1) => x => f1(f0(x)));
File.WriteAllText("output.text", map(File.ReadAllText("test.txt")));
调用map("Hello")
会产生"Hxllx"
,给定我上面的map
代码。