加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

可靠的函数来获取Swift中字符串中子字符串的位置

发布时间:2020-12-14 04:41:44 所属栏目:百科 来源:网络整理
导读:这对英语很有用: public static func posOf(needle: String,haystack: String) - Int { return haystack.distance(from: haystack.startIndex,to: (haystack.range(of: needle)?.lowerBound)!)} 但对于外来字符,返回的值总是太小.例如,“??”被认为是一个单
这对英语很有用:

public static func posOf(needle: String,haystack: String) -> Int {
    return haystack.distance(from: haystack.startIndex,to: (haystack.range(of: needle)?.lowerBound)!)
}

但对于外来字符,返回的值总是太小.例如,“??”被认为是一个单位而不是2个单位.

posOf(needle: "???",haystack: "?? ???? ?? ???? ????? ???? ??? ??? ???? ???") // 21

我后来在NSRange中使用21(位置:长度:),其中需要28才能使NSRange正常工作.

解决方法

Swift String是Characters和每个Character的集合
代表“扩展的Unicode字形集群”.

NSString是UTF-16代码单元的集合.

例:

print("??".characters.count) // 1
print(("??" as NSString).length) // 2

Swift String范围表示为Range< String.Index>,
和NSString范围表示为NSRange.

您的函数从头开始计算字符数
干草堆到针的开头,这是不同的
从UTF-16代码点的数量.

如果你需要“NSRange兼容”
字符数,那么最简单的方法就是使用
NSString的range(of :)方法:

let haystack = "?? ???? ?? ???? ????? ???? ??? ??? ???? ???"
let needle = "???"

if let range = haystack.range(of: needle) {
    let pos = haystack.distance(from: haystack.startIndex,to: range.lowerBound)
    print(pos) // 21
}

let nsRange = (haystack as NSString).range(of: needle)
if nsRange.location != NSNotFound {
    print(nsRange.location) // 31
}

或者,使用Swift字符串的utf16视图
计算UTF-16代码单位:

if let range = haystack.range(of: needle) {
    let lower16 = range.lowerBound.samePosition(in: haystack.utf16)
    let pos = haystack.utf16.distance(from: haystack.utf16.startIndex,to: lower16)
    print(pos) // 31
}

(例如,参见
NSRange to Range<String.Index>更多方法在Range< String.Index>之间进行转换和NSRange).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读