我有两个字符串,想判断这两个字符串是否以相同的子字符串开头。
str1 = "The cat is black. jkhdkjhdsjhd"
str2 = "The cat is black and white."
str1.starts_with_substring? str2
returns "The cat is black"
str1.starts_with_substring? "The cat"
returns "The cat"
str1.starts_with_substring? "Hello, World!""
returns nil
我想我可以用一个迭代器来做到这一点,但我希望有更多内置的东西。
最佳答案
您可以为此使用 start_with?
和 all?
:
str1 = "The cat is black. jkhdkjhdsjhd"
str2 = "The cat is black and white."
p [str1, str2].all? { |str| str.start_with?('The cat is') } # true
p [str1, str2].all? { |str| str.start_with?('The cat is not') } # false
从 Ruby 2.5 开始 Enumerable#any?, all?, none?还有一个?接受一个模式作为参数,你可以传递一个正则表达式来检查每个字符串是否以该子字符串开头:
str1 = "The cat is black. jkhdkjhdsjhd"
str2 = "The cat is black and white."
str3 = "renuncia Piñera The cat is black and white."
p [str1, str2].all?(/\AThe cat is /) # true
p [str1, str2, str3].all?(/\AThe cat is /) # false
在评论中看到问题后,这可能会起作用:
str1 = "The cat is black."
str2 = "The cat is black and white."
str3 = "The cat"
def all_substring?(sentences)
length = sentences.min.length
sentences.map { |sentence| sentence[0...length] }.uniq == [sentences.sample[0...length]]
end
p all_substring?([str1, str2, str3]) # true
如果你不能事先知道是否有一个要查找的子串,我认为你可以使用最小的句子作为子串。
关于ruby - 如何确定两个字符串是否以 ruby 中的相同子字符串开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683506/