2015-11-26 78 views
0

嘿,我試圖替換文件中的一些符號。我製作了字典 ,我可以將其替換爲我輸入的字符串。如何閱讀我的文件, 做我的替換並保存到另一個?替換文件c中的符號#

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

爲了使回答者或其他有類似問題的人更容易,請編輯添加一個特定的問題陳述 - 「不起作用」可以假設,但* how *不起作用?什麼錯誤信息或不正確的行爲是特徵? –

+0

字典中的每個KeyValuePair具有相同的鍵和值,所以看起來毫無用處。更重要的是,爲什麼一次一個字符替換字符,一次只替換所有文件內容字符串? –

回答

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代碼。

+0

這是一件藝術品。我喜歡! –

+0

但也不容易理解。 –