2011-05-06 64 views
0

我需要通过一个字符串列表并计算重复的次数,然后用一行中出现次数的字符串打印到文件。这是我的,但我只需要打印一次字符串和它的数量。组重复计数

Do 
     line = LineInput(1) 
     Trim(line) 
     If line = temp Then 
      counter += 1 
     Else 
      counter = 1 
     End If 
     temp = line 
     swriter.WriteLine(line & " " & counter.ToString) 
     swriter.Flush() 

    Loop While Not EOF(1) 

我的大脑只是今天没有发挥作用..

回答

1

你应该使用像一个Dictionary计数字符串。

Dim dict As New Dictionary(Of String, Integer) 
Do 
    line = LineInput(1) 
    line = Trim(line) 
    If dict.ContainsKey(line) Then 
    dict(line) += 1 
    Else 
    dict.Add(line, 1) 
    End If 
Loop While Not EOF(1) 

,然后打印出的元素在字典

For Each line As String In dict.Keys 
    swriter.WriteLine(line & " " & dict(line)) 
    swriter.Flush() 
Next 
2

你也可以使用LINQ:

Dim dups = From x In IO.File.ReadAllLines("TextFile1.txt") _ 
       Group By line Into Group _ 
       Where Group.Count > 1 _ 
       Let count = Group.Count() _ 
       Order By count Descending _ 
       Select New With { _ 
        Key .Value = x, _ 
        Key .Count = count _ 
       } 

For Each d In dups 
    swriter.WriteLine(String.Format("duplicate: {0} count: {1}", d.Value, d.Count)) 
    swriter.Flush() 
Next