【问题标题】:Find Common text occurrences in multiple strings在多个字符串中查找常见的文本出现
【发布时间】:2014-01-15 01:35:42
【问题描述】:

我试图找出一种方法来比较两个字符串并返回它们的“常用”词,因为字符串总是小写的,我想为此创建一个函数..例如

str1 = "this is a test"
str2 = "saldkasl test asdasd"

result = stringcompare(str1, str2) 'returns "test"

两个字符串之间的共同词应该是“test” 如果两个字符串有两个或多个常用词,则该​​函数应连接字符串

str1 = "this is another test"
str2 = "another asdsada test asdsa"
result = stringcompare(str1, str2) ' returns "another test"

我找到了一个有用的link,它给了我一个想法,但不知何故确实缺少一些东西

我现在正在做的伪代码是这样的,

**

'1st: separate the words by every space, " ", then store it in an array or list 
'2nd: compare each item on the list, if equal then store to variable 'result'

**

这样好吗?我认为这很慢,也许有人对此有更好的方法..谢谢

【问题讨论】:

  • 我认为这已经是一个不错的解决方案了。你如何将它存储在容器中?也许这就是问题所在。
  • 将每个字符串拆分为数组,将它们连接起来,然后通过 linq 聚合内容,并仅过滤与您的字符串一样多的文本,例如,如果您有 3 个字符串,则过滤计数文本等于 3

标签: vb.net string


【解决方案1】:

在 VS 2013 中测量,以下解决方案平均比 Guffa 快 20%:

Dim str1 As String = "this is another test"
Dim str2 As String = "another asdsada test asdsa"
Dim result As String = String.Join(" ", str1.Split(" "c).
                              Intersect(str2.Split(" "c)))

通过将每个解决方案循环 100000 次并使用 StopWatch 测量时间来获得结果。

【讨论】:

  • 当我尝试这个时,错误显示:“相交不是 System.Array 的成员”。我正在使用 vb.net 2005
  • @Malky.Kid:以上是 Visual Studio 2010+。你有什么理由需要坚持 2005 年吗?
  • 我明白了,谢谢。办公室不想投资新版本的visual studio :(
  • @Malky.Kid:你有两个选择 - 自己实现 Intersect(这应该不会太难),或者使用 Linq Bridge,链接 from this question
  • @Neolisk:即使每个字符串包含 8 个单词,我也会得到休息。
【解决方案2】:

对第一个字符串中的单词使用哈希集,然后您可以遍历第二个字符串中的单词并检查它们是否存在于第一个字符串中,并获得接近 O(n) 的性能:

Dim first As New HashSet(Of String)(str1.Split(" "c))
Dim result As String() = str2.Split(" "c).Where(Function(s) first.Contains(s)).ToArray()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2013-08-25
    • 2014-05-24
    • 2017-03-30
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多