循环遍历字符串数组并与之前的值进行比较

时间:2014-03-02 01:59:48

标签: c# arrays string

我需要遍历一个字符串数组,并知道我之前是否看过一个特定的字符串值。通常,我会用其他语言写这样的东西:

String oldValue="";
String newValue;
for (i=0;i<myarray.Length;i++)
{
    newValue=myarray[i];
    if (oldValue==newValue)
        break;
    ...

    oldValue=newValue;

}

但是,这在C#中不起作用,因为字符串是不可变的。如果我只是替换整个字符串,看起来我可以使用正则表达式执行此操作,但这似乎是额外的开销。其他人以前怎么处理过这个?

谢谢

2 个答案:

答案 0 :(得分:5)

我不确定我是否理解你的问题,但如果你想要检测数组中重复的第一个字符串,你需要记住所有这些。我建议使用HashSet,所以至少它在O(n)中运行,如下所示:

HashSet<string> prevSet = new HashSet<string>();

foreach ( string str in myArray )
  if ( !prevSet.Add(str) ) return str;

答案 1 :(得分:1)

您可以这样做以制作单词频率列表:

var frequency =
    myarray
        .GroupBy(x => x)
        .Select(x => new
        {
            Value = x.Key,
            Count = x.Count(),
        });

然后,您只需将此列表过滤到Count > 1