从Swift中的两个不同字符串返回匹配的单词作为字符串
我有:从Swift中的两个不同字符串返回匹配的单词作为字符串,swift,string,Swift,String,我有:str1=“这是我工作的第一天”和str2=“这是伟大的一天”,我想将前面两个字符串str1和str2中匹配的单词作为字符串返回,然后将它们存储在一个新变量中 新变量str3:String应包含以下文本“this is day” 我在搜索中找到了此项,但我需要返回一个包含匹配项的字符串 func isAnagram() -> Bool { let str1 = "this is the first day in my work" let str2 = "this i
str1=“这是我工作的第一天”
和str2=“这是伟大的一天”
,我想将前面两个字符串str1和str2中匹配的单词作为字符串返回,然后将它们存储在一个新变量中
新变量str3:String
应包含以下文本“this is day”
我在搜索中找到了此项,但我需要返回一个包含匹配项的字符串
func isAnagram() -> Bool {
let str1 = "this is the first day in my work"
let str2 = "this is a great day"
func countedSet(string: String) -> NSCountedSet {
let array = string.map { (character) -> String in
return String(character)
}
return NSCountedSet(array: array)
}
return countedSet(string: str1).isEqual(countedSet(string: str2))
}
如果最后一个字符串中的顺序无关紧要,这将是一个简单的解决方案:
let str1 = "this is the first day in my work"
let str2 = "this is a great day"
let words1 = Set(str1.split(separator: " "))
let words2 = Set(str2.split(separator: " "))
let str3 = words1.intersection(words2).reduce("") { $0 + $1 + " "}
如果订单重要:
...
let str3 = words1.intersection(words2).sorted {
words1.index(of: $0)! < words1.index(of: $1)!
}.reduce("") { $0 + $1 + " "}
。。。
设str3=words1.intersection(words2).sorted{
words1.index(of:$0)!
您可以使用String
方法枚举子字符串(在:范围内)
使用。byWords
选项获取字符串句子中的单词,并使用筛选器删除第二个字符串中不包含的单词:
extension StringProtocol where Index == String.Index {
var words: [String] {
var result: [String] = []
enumerateSubstrings(in: startIndex..., options: .byWords) { (substring, _, _, _) in
result.append(substring!)
}
return result
}
func matchingWords(in string: String) -> [String] {
return string.words.filter(words.contains)
}
}
请注意,这将保留出现的顺序,如果字符串中有标点符号,则不会失败:
let str1 = "this is the first day in my work"
let str2 = "this is a great day"
let matchingWords = str1.matchingWords(in: str2) // ["this", "is", "day"]
let str3 = matchingWords.joined(separator: " ") // "this is day"
非常感谢。现在,这些代码发生了什么?它是返回了错误的信息还是什么都没有?或者什么?你发布的代码与你问题中的描述无关。我想返回一个带有匹配单词@caseywest的字符串
reduce
可以替换为:let str3=Array(words1.intersection(words2))。joined(分隔符:“”)
请注意,您的上一个实现没有保留顺序。为什么要使用reduce而不是join方法<代码>单词1.交叉点(单词2).连接(分隔符:“”)