使用数组替换字符串

时间:2015-11-26 19:10:11

标签: c# arrays streamreader

我有一个从csv文件中获取的两个数组,我想检查第一个数组的当前输出并输出第二个数组,例如 “你好,LOL”输出“Hello,Laugh out loud” 我用过

int candidateLength = 20 ; 

Candidate[] candidates = new Candidate[candidateLength ];

for(int i=0 ; i<candidates.Length ; i++)
{
   candidates[i] = new Candidate();
}

存储数组并在其中包含正确的信息,我只是不知道如何检查第一个列表中的字符串并将其更改为第二个。

1 个答案:

答案 0 :(得分:0)

您应该使用Dictionary代替List进行此操作。此外,您可以使用File.ReadAllLines读取文件中的所有行而不是循环。

// I replace your code with linq
Dictionary<string, string> dictionary = 
  File.ReadAllLines("@filelocation").Select(l => l.Split(',')).ToDictionary(k =>
k[0], v => v[1]); 

string input = "Hello, LOL" ; 

var thekey =  dictionary.Keys.FirstOrDefault(k => input.Contains(k));

if (thekey != null) // Replacement was found 
{
    input = input.Replace(thekey, dictionary[thekey]);    
}

// Should print Hello, Laugh out loud
Console.WriteLine(input) ; 
相关问题