【发布时间】:2016-01-23 15:31:30
【问题描述】:
我的输入是一个字符串,它可能是人的名字、姓氏、组合,甚至是两者的一部分,按特定顺序排列
Class {
first = 'John' // just simple string
last = 'Smith' // just simple string
middle = 'Mark Bill' // this is often empty string, but may contain multiple, divided by spaces. ('' or 'Mark Bill')
hasPresent(what){
return true || false
}
}
如果用户的输入是“John”,我们的 John 的 hasPresent 方法应该返回 true
其他情况:
"input" => expected result
"Smith" => true
"mark" => true
"John Mark" => true
"hn mar" => true
"m" => true
" " => true
"John John" => false
"John Mark John" => false
"Jo Mark" => false
"John rk" => false
"n n n" => false
为了更好地理解,想象一下,您可以按任何顺序排列此人的姓名,只要您只使用一次即可。然后获取输入并将其与˙indexOf˙函数匹配。也就是说,为什么˙"John rk"˙ 是假的,无论您多么努力,都可以按特定顺序将具有˙"john rk"˙ 的字符串组合在一起。你可以有˙"John Mark"˙,但是这不会匹配使用˙indexOf˙。
根据我们的名字,我们可以匹配任何匹配任何以下字符串的内容
"John Smith Mark Bill","John Mark Smith Bill","John Bill Smith Mark","John Mark Smith Bill","John Smith Bill Mark", "John Mark Bill Smith" etc
我认为,使用所有名称(名字、姓氏和分隔的中间名)创建数组并匹配所有可能的组合可能是可行的方法,但由于必须在此之前完成,我想知道是否有更好的方式。
如果没有更好的方法,如何以尽可能少的处理能力从数组中做出所有可能的组合?
【问题讨论】:
-
为什么
"John rk"会返回false? -
就好像你会在
"Jonh Mark"上做indexOf一样 -
逻辑不清楚,在这里。不确定
"hn mar"如何返回true,而"John rk"可以返回false?请参阅 "如果用户的输入是 'John',我们的 John 的 hasPresent 方法应该返回 true" 处的 OP。"rk"如何在输入字符串的开头否定"John"? , 其中字符串的两个部分都以全名找到 -
由于我们严格需要将整个输入与人名的任何顺序相匹配,因此
John ma很重要。如果他的名字的顺序正确的话,可以不间断地在一件中找到它 -
@JuanBoca 的更新答案应该满足要求,保留
"John rk"的情况
标签: javascript arrays match string-matching