比较数组中的元素,看看字符串中是不是有重复项
Posted
技术标签:
【中文标题】比较数组中的元素,看看字符串中是不是有重复项【英文标题】:Compare the elements in the array to see if there are duplicates in the string比较数组中的元素,看看字符串中是否有重复项 【发布时间】:2021-06-10 03:09:57 【问题描述】:目前,我在将数组与字符串进行比较时遇到问题。我有 2 个数组,想知道这 2 个数组中的元素是否在字符串中
let resultString = "STEREON10.000 4ailthameGrinreD NOCHIMINNICHNUÖC-LOINHÀ GIAIDACBIET2ty UnOMMOSTCRShitConDONG FlimChineCrJ045 Dòketquásoan: XSHCM goi 7181 8186-8110°593364THUBAY6A7 05-6-2021teIntaiKNInTaiChínhTP.HCM"
let code_province:[String] = ["xsag", "xsbd", "xsbdi", "xsbl","xsbp",
"xsbt", "xsbth", "xscm", "xsct", "xsdl",
"xsdlk", "xsdn", "xsdng", "xsdno", "xsdt",
"xsgl", "xshcm", "xshg", "xskg", "xskh",
"xskt", "xsla", "xsmb", "xsnt", "xspy",
"xsqb", "xsqng", "xsqnm", "xsqt", "xsst",
"xstg", "xstn", "xstth", "xstv", "xsvl",
"xsvt", "xsbri",]
let name_Province:[String] = ["angiang","binhduong","binhdinh","baclieu", "binhphuoc","bentre", "binhthuan", "camau", "cantho", "dalat","daklak", "dongnai", "daNang", "daknong", "dongthap","gialai", "hcm", "haugiang", "kiengiang", "khanhhoa","kontum", "longan", "mienbac", "ninhthuan", "phuyen","quangbinh", "quangNgai", "quangnam", "quangtri", "soctrang","tiengiang", "tayninh", "thuat.hue", "travinh", "vinhlong","vungtau","baria"]
【问题讨论】:
请添加一些您尝试过的代码。另外,添加您面临的问题。 可能是let resultStringSplit = resultString.components(separatedBy: " "); let contains = !Set(code_province).intersection(resultStringSplit).isEmpty || !Set(name_Province).intersection(resultStringSplit).isEmpty; print(contains)
?
你不能指望社区给你一个算法的解决方案。有很多字符串搜索算法。这实际上不是问题。感觉就像你想要有人为你做这项工作。做这项工作。开始here。然后实施它。同样对于@aheze 评论,这不起作用,因为他们询问两个数组之一中的字符串是否为“IN THE STRING”。您的评论假定他们正在寻找的字符串由未指定的空格分隔。
【参考方案1】:
这是一种方法:
let f: (String) -> String? = resultString.localizedStandardContains($0) ? $0 : nil
let provincesInResult = code_province.compactMap(f)
let namesInResult = name_Province.compactMap(f)
我们从字符串列表中映射要搜索的事物列表,如果没有找到则映射到 nil,如果找到则映射到字符串。然后我们压缩结果,只留下一个找到的列表。这可能是 0、1 或更多,因此请考虑这些可能性。
【讨论】:
以上是关于比较数组中的元素,看看字符串中是不是有重复项的主要内容,如果未能解决你的问题,请参考以下文章