最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift中判断字符串是否以某种字符串开头+并截取其中部分作为子字符串

Swift crifan 3498浏览 0评论
                print(“phoneDigitsStr=\(phoneDigitsStr)”) //+86138xxxxxxxx
                let prefix = phoneDigitsStr.substringToIndex(Index(3))
                if prefix == “+86” {
                    let realPhoneNumber = phoneDigitsStr.substringFromIndex(<#T##index: Index##Index#>)
                }

写了半天,都没搞定。

也去尝试:

startWith之类的,但是没有这个函数。

也是了Prefix之类的,也没找到。

swift string start with

swift中字符串截取方法(substring) – swift迷

ios – Swift startsWith method? – Stack Overflow

How do I check if a string contains another string in Swift? – Stack Overflow

ios – How to check what a String starts with (prefix) or ends with (suffix) in Swift – Stack Overflow

发现其中有:

hasPrefix

最后用:

            if let phoneDigits = phoneNumber.valueForKey(“digits”){
                let phoneDigitsStr = String(phoneDigits)
                print(“phoneDigitsStr=\(phoneDigitsStr)”) //+86138xxxxxxx
                if phoneDigitsStr.hasPrefix(“+86”) {
                    let prefixIndex = phoneDigitsStr.startIndex.advancedBy(3)
                    print(“prefixIndex=\(prefixIndex)”) //3
                    let realPhoneNumber = phoneDigitsStr.substringFromIndex(prefixIndex)
                    print(“realPhoneNumber=\(realPhoneNumber)”) //138xxxxxxx
                }
            }

即可。

转载请注明:在路上 » [已解决]swift中判断字符串是否以某种字符串开头+并截取其中部分作为子字符串

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.168 seconds, using 22.08MB memory