替换文件c#中的符号

时间:2015-11-26 00:19:44

标签: c# arrays file text input

  嘿,我正在尝试替换文件中的一些符号。我做了字典   我可以在我输入的字符串中替换它。如何阅读我的文件,   我替换并将其保存到另一个?

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;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

尝试这样做:

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