如何将一个字符串与另一个之间有空格的字符串进行比较 [英] How to compare a string with another where the one has space in between
本文介绍了如何将一个字符串与另一个之间有空格的字符串进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何比较这两个字符串:
How do I compare these two string :
val a = "fit bit versa"
val b = "fitbit"
另一个例子
val a = "go pro hero 6"
val b = "gopro"
另一个例子
val a = "hero go pro 6"
val b = "gopro"
另一个例子
val a = "hero 6 go pro"
val b = "gopro"
我想为上述比较获得真实"但不是在这里:
I want to get "true" for the above comparisons but not here:
val a = "vegan protein powder"
val b = "vega"
这应该是假的.
目前我在做:
def matchPattern(a:String, b: String):String=
{
val dd = a.split(" ")
val result = dd.map(_.toLowerCase())
if(result contains b.toLowerCase) true
else false
}
这适用于最后一种情况,但不适用于其他情况.
This works for last case but not the rest.
有什么建议吗?
推荐答案
这是一种使用 sliding(i)
的方法,其中 i
的范围从 2 到 word-count ina
,组装所有可能连接的相邻单词的列表.然后检查 b
是否与列表中的任何元素完全匹配,如下所示:
Here's one approach using sliding(i)
, where i
ranges from 2 to word-count in a
, to assemble a list of all possible concatenated adjacent words. It is then checked to see whether b
exactly matches any of the elements in the list, as shown below:
def matchPattern(a: String, b: String): Boolean = {
val words = a.toLowerCase.split("\\s+")
val concats = (2 to words.size).foldLeft(words)(
(acc, i) => acc ++ words.sliding(i).map(_.mkString)
)
concats contains b.toLowerCase
}
matchPattern("Hero go Pro 6", "gopro")
// res1: Boolean = true
matchPattern("Hero go Pro 6", "gopro6")
// res2: Boolean = true
matchPattern("Vegan protein powder", "vega")
// res3: Boolean = false
这篇关于如何将一个字符串与另一个之间有空格的字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文