簡體   English   中英

如何檢測另一個字符串中1個字符串中是否存在子字符串?

[英]How do I detect the presence of a substring in 1 string in another string?

假設我有一個字符串"rubinassociatespa" ,我想要做的是檢測該字符串中包含3個字符或更多字符串的任何子字符串,在任何其他字符串中。

例如,應檢測以下字符串:

  • rubin
  • associates
  • spa
  • ass
  • rub

但是不應該檢測到的是以下字符串:

  • rob
  • cpa
  • dea
  • ru或我的原始字符串中沒有出現的任何其他子字符串,或者短於3個字符。

基本上,我有一個字符串,我正在比較許多其他字符串,我只想匹配組成原始字符串的子字符串的字符串。

我希望這很清楚。

str = "rubinassociatespa"

arr = %w| rubin associates spa ass rub rob cpa dea ru |
  #=> ["rubin", "associates", "spa", "ass", "rub", "rob", "cpa", "dea", "ru"]

只需使用String #include?

def substring?(str, s)
  (s.size >= 3) ? str.include?(s) : false
end

arr.each { |s| puts "#{s}: #{substring? str, s}" }
  # rubin: true
  # associates: true
  # spa: true
  # ass: true
  # rub: true
  # rob: false
  # cpa: false
  # dea: false
  # ru: false

你可以使用match

str = "rubinassociatespa"

test_str = "associates"

str.match(test_str) #=> #<MatchData "associates">
str.match(test_str).to_s #=> "associates"

test_str = 'rob'

str.match(test_str) #=> nil

因此,如果test_strstr的子str ,則match方法將返回整個test_str ,否則返回nil

if test_str.length >= 3 && str.match(test_str)
  # do stuff here. 
end

首先,您需要一個可接受的字符串列表。 https://github.com/first20hours/google-10000-english這樣的東西可能會很有用。

其次,您需要一種允許快速查找以查看單詞是否有效的數據結構。 我會為此使用Bloom Filter。 如果您不想自己實現它,這個gem可能很有用: https//github.com/igrigorik/bloomfilter-rb

然后,您需要使用有效單詞列表中所有有效單詞的列表啟動Bloom過濾器。

然后,對於字符串中的每個子字符串,您希望在bloom過濾器結構中進行查找,以查看它是否在有效單詞列表中。 請參閱此示例以了解如何獲取所有子字符串: 拆分字符串以獲取Ruby的所有子字符串的最佳方法是什么?

如果bloom過濾器返回true,則需要進行二次檢查以確認它實際上在列表中,因為Bloom過濾器是概率數據結構。 您可能需要使用數據庫來存儲有效的單詞列表集合,因此您可以只進行數據庫查找以確認它是否有效。

我希望這可以讓你了解如何繼續。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM