[英]Detect if a string consists of a substring of a string
我讓用戶輸入了字符串A,例如“ sun晴”。 我在數據庫“ sun cloud rain”中有一個字符串B。 如何檢測字符串A的一部分是否為字符串B的一部分?
我使用了@sky.include?(activity.sky)
,其中@sky
是字符串A , activity.sky
是字符串B。 僅當字符串A為sun時,此方法才有效。
您可以將字符串分成兩個數組
a = "sun is clear".split
b = "sun cloud rain".split
並計算交集
a & b
# => ["sun"]
(a & b).empty?
# => false
如果交集不為空,則它們共享零件。 否則,您也可以計算a
- b
的差
(a - b).size == a.size
# => false
要匹配字符串A的單詞a是字符串B的單詞之一,請使用以下命令:
activity.sky.split( /\s+/ ).any? {|s| @sky.include?(s) }
如果A
和B
本身都不包含單詞的重復項,則可以這樣檢查:
A = "sun is clear"
B = "sun cloud rain"
"#{A} #{B}" =~ /\b(\w+)\b.*\b\1\b/ # => 0 (non-nil means there is a common word)
A = "sun is clear"
B = "cloud rain"
"#{A} #{B}" =~ /\b(\w+)\b.*\b\1\b/ # => nil (nil means there is no common word)
否則,您可以在兩個字符串之間插入一些非字母的非空格字符(例如"|"
):
A = "sun is sun"
B = "sun cloud rain"
"#{A}|#{B}" =~ /\b(\w+)\b.*|.*\b\1\b/ # => 0
A = "sun is sun"
B = "cloud rain"
"#{A}|#{B}" =~ /\b(\w+)\b.*|.*\b\1\b/ # => nil
拆分然后放置&運算符
(@sky.split(" ") & activity.sky.split(" ")).empty?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.