Split String into groups with specific length

后端 未结 10 1844
囚心锁ツ
囚心锁ツ 2021-01-05 09:32

How can I split the given String in Swift into groups with given length, reading from right to left?

For example, I have string 123456789 a

10条回答
  •  甜味超标
    2021-01-05 10:23

    Here is a version using NSRegularExpressions

    func splitedString(string: String, length: Int) -> [String] {
        var groups = [String]()
        let regexString = "(\\d{1,\(length)})"
        do {
            let regex = try NSRegularExpression(pattern: regexString, options: .CaseInsensitive)
            let matches = regex.matchesInString(string, options: .ReportCompletion, range: NSMakeRange(0, string.characters.count))
            let nsstring = string as NSString
            matches.forEach {
                let group = nsstring.substringWithRange($0.range) as String
                groups.append(group)
            }
        } catch let error as NSError {
            print("Bad Regex Format = \(error)")
        }
    
        return groups
    }
    

提交回复
热议问题