我需要查看字符串列表并计算重复项数,然后将包含一行中出现次数的字符串打印到文件中。这是我所拥有的,但我只需要打印一次字符串及其计数。
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)
我的大脑今天不起作用..
答案 0 :(得分: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
答案 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