如何将Swift中给定的String
分成给定长度的组,从右到左阅读?
例如,我有字符串123456789
,组长度为3.字符串应分为3组:123
,456
,789
。字符串1234567
将分为1
,234
,567
那么,你能在Swift中编写一些不错的代码吗?
func splitedString(string: String, length: Int) -> [String] {
}
BTW尝试了函数split()
,但据我所知它只能找到一些符号
答案 0 :(得分:2)
只是为了加入这个非常拥挤的比赛(SwiftStub):
func splitedString(string: String, length: Int) -> [String] {
var result = [String]()
for var i = 0; i < string.characters.count; i += length {
let endIndex = string.endIndex.advancedBy(-i)
let startIndex = endIndex.advancedBy(-length, limit: string.startIndex)
result.append(string[startIndex..<endIndex])
}
return result.reverse()
}
或者如果你感觉功能正常:
func splitedString2(string: String, length: Int) -> [String] {
return 0.stride(to: string.characters.count, by: length)
.reverse()
.map {
i -> String in
let endIndex = string.endIndex.advancedBy(-i)
let startIndex = endIndex.advancedBy(-length, limit: string.startIndex)
return string[startIndex..<endIndex]
}
}
答案 1 :(得分:1)
这是我想到的最重要的事情。我敢打赌有更好的方法,所以我鼓励你继续努力。
func splitedString(string: String, length: Int) -> [String] {
var groups = [String]()
var currentGroup = ""
for index in string.startIndex..<string.endIndex {
currentGroup.append(string[index])
if currentGroup.characters.count == 3 {
groups.append(currentGroup)
currentGroup = ""
}
}
if currentGroup.characters.count > 0 {
groups.append(currentGroup)
}
return groups
}
以下是我的测试
let firstString = "123456789"
let groups = splitedString(firstString, length: 3)
// Returned ["123", "456", "789"]
let secondString = "1234567"
let moreGroups = splitedString(secondString, length: 3)
// Returned ["123", "456", "7"]
答案 2 :(得分:1)
这是使用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
}
答案 3 :(得分:1)
这是使用功能编程的另一个版本。
extension String{
func splitedString(length: Int) -> [String]{
guard length > 0 else { return [] }
let range = 0..<((characters.count+length-1)/length)
let indices = range.map{ length*$0..<min(length*($0+1),characters.count) }
return indices
.map{ characters.reverse()[$0.startIndex..<$0.endIndex] }
.map( String.init )
}
}
"1234567890".splitedString(3)
答案 4 :(得分:1)
Swift 4
我认为扩展方法更有用。
extension String{
public func splitedBy(length: Int) -> [String] {
var result = [String]()
for i in stride(from: 0, to: self.characters.count, by: length) {
let endIndex = self.index(self.endIndex, offsetBy: -i)
let startIndex = self.index(endIndex, offsetBy: -length, limitedBy: self.startIndex) ?? self.startIndex
result.append(String(self[startIndex..<endIndex]))
}
return result.reversed()
}
}
使用示例:
Swift.debugPrint("123456789".splitedBy(length: 4))
// Returned ["1", "2345", "6789"]
答案 5 :(得分:1)
快捷键4
我根据功能参数对answer given by cafedeichi进行了调整,使其可以从左到右或从右到左操作,因此它更具通用性。
extension String {
/// Splits a string into groups of `every` n characters, grouping from left-to-right by default. If `backwards` is true, right-to-left.
public func split(every: Int, backwards: Bool = false) -> [String] {
var result = [String]()
for i in stride(from: 0, to: self.count, by: every) {
switch backwards {
case true:
let endIndex = self.index(self.endIndex, offsetBy: -i)
let startIndex = self.index(endIndex, offsetBy: -every, limitedBy: self.startIndex) ?? self.startIndex
result.insert(String(self[startIndex..<endIndex]), at: 0)
case false:
let startIndex = self.index(self.startIndex, offsetBy: i)
let endIndex = self.index(startIndex, offsetBy: every, limitedBy: self.endIndex) ?? self.endIndex
result.append(String(self[startIndex..<endIndex]))
}
}
return result
}
}
示例:
"abcde".split(every: 2) // ["ab", "cd", "e"]
"abcde".split(every: 2, backwards: true) // ["a", "bc", "de"]
"abcde".split(every: 4) // ["abcd", "e"]
"abcde".split(every: 4, backwards: true) // ["a", "bcde"]
答案 6 :(得分:0)
我做了这样的事情,无法创造更好看的东西,但其结果与问题相符:
func splitedString(string: String, lenght: Int) -> [String] {
var result = [String](), count = 0, line = ""
for c in string.characters.reverse() {
count++; line.append(c)
if count == lenght {count = 0; result.append(String(line.characters.reverse())); line = ""}
}
if !line.isEmpty {result.append(String(line.characters.reverse()))}
return result.reverse()
}
答案 7 :(得分:0)
可能有更优雅的解决方案,但这有效:
func splitedString(string: String, length: Int) -> [String] {
let string = Array(string.characters)
let firstGroupLength = string.count % length
var result: [String] = []
var group = ""
if firstGroupLength > 0 {
for i in 0..<firstGroupLength {
group.append(string[i])
}
result.append(String(group))
group = ""
}
for i in firstGroupLength..<string.count {
group.append(string[i])
if group.characters.count == length {
result.append(group)
group = ""
}
}
return result
}
splitedString("abcdefg", length: 2) // ["a", "bc", "de", "fg"]
splitedString("1234567", length: 3) // ["1", "234", "567"]
答案 8 :(得分:0)
使用子串的另一种解决方案:
func splitStringByIntervals(str: String, interval: Int) -> [String] {
let st = String(str.characters.reverse())
let length = st.characters.count
var groups = [String]()
for (var i = 0; i < length; i += interval) {
groups.append((st as NSString).substringWithRange(NSRange(location: i, length: min(interval, length - i))))
}
return groups.map{ String($0.characters.reverse())}.reverse()
}
输出:
for element in splitStringByIntervals("1234567", interval: 3) {
print(element)
}
是:
1
234
567
答案 9 :(得分:0)
func split(every length:Int) -> [Substring] {
guard length > 0 && length < count else { return [suffix(from:startIndex)] }
return (0 ... (count - 1) / length).map { dropFirst($0 * length).prefix(length) }
}
func split(backwardsEvery length:Int) -> [Substring] {
guard length > 0 && length < count else { return [suffix(from:startIndex)] }
return (0 ... (count - 1) / length).map { dropLast($0 * length).suffix(length) }.reversed()
}
测试:
XCTAssertEqual("0123456789".split(every:2), ["01", "23", "45", "67", "89"])
XCTAssertEqual("0123456789".split(backwardsEvery:2), ["01", "23", "45", "67", "89"])
XCTAssertEqual("0123456789".split(every:3), ["012", "345", "678", "9"])
XCTAssertEqual("0123456789".split(backwardsEvery:3), ["0", "123", "456", "789"])
XCTAssertEqual("0123456789".split(every:4), ["0123", "4567", "89"])
XCTAssertEqual("0123456789".split(backwardsEvery:4), ["01", "2345", "6789"])