如何将字符串拆分为等长的子字符串 [英] How to split a string into substrings of equal length

查看:273
本文介绍了如何将字符串拆分为等长的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以

split("There are fourty-eight characters in this string", 20)

应该返回

["There are fourty-eig", "ht characters in thi","s string"]

如果我使currentIndex = string.startIndex,然后尝试使它比string.endIndex更进一步(),我将收到严重错误:无法递增endIndex",然后再检查currentIndex是否<. string.endIndex,因此下面的代码不起作用

If I make currentIndex = string.startIndex and then try to advance() it further than a string.endIndex, I get "fatal error: can not increment endIndex" before I check if my currentIndex < string.endIndex so the code below doesn't work

var string = "12345"
var currentIndex = string.startIndex
currentIndex = advance(currentIndex, 6)
if currentIndex > string.endIndex {currentIndex = string.endIndex}

推荐答案

我刚刚在SO上回答了类似的问题,并认为我可以提供更简洁的解决方案:

I just answered a similar question on SO and thought I can provide a more concise solution:

func split(str: String, _ count: Int) -> [String] {
    return 0.stride(to: str.characters.count, by: count).map { i -> String in
        let startIndex = str.startIndex.advancedBy(i)
        let endIndex   = startIndex.advancedBy(count, limit: str.endIndex)
        return str[startIndex..<endIndex]
    }
}

雨燕3

func split(_ str: String, _ count: Int) -> [String] {
    return stride(from: 0, to: str.characters.count, by: count).map { i -> String in
        let startIndex = str.index(str.startIndex, offsetBy: i)
        let endIndex   = str.index(startIndex, offsetBy: count, limitedBy: str.endIndex) ?? str.endIndex
        return str[startIndex..<endIndex]
    }
}

雨燕4

更改为while循环以提高效率,并通过受欢迎的请求使其成为String的扩展名:

Swift 4

Changed to a while loop for better efficiency and made into a String's extension by popular request:

extension String {
    func split(by length: Int) -> [String] {
        var startIndex = self.startIndex
        var results = [Substring]()

        while startIndex < self.endIndex {
            let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            results.append(self[startIndex..<endIndex])
            startIndex = endIndex
        }

        return results.map { String($0) }
    }
}

这篇关于如何将字符串拆分为等长的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆