我想按给定大小2
示例:
字符串"1234567"
和输出应为["12", "34", "56","7"]
答案 0 :(得分:5)
您可以将字符串转换为字符数组,并使用stride(from:, to:, by:)
方法每n个元素迭代字符并使用map返回它们:
extension String {
func group(of n: Int) -> [String] {
let chars = Array(self)
return stride(from: 0, to: chars.count, by: n).map {
String(chars[$0..<min($0+n, chars.count)])
}
}
}
let numbers = "1234567"
let grouped = numbers.group(of: 2)
print(grouped) // ["12", "34", "56", "7"]
修改/更新强>:
如果要将最后一组字符附加到结果数组的最后一个元素,则需要检查结果数组中是否有最后一个元素,以及每个字符串字符数是否小于之前的组大小将每个元素附加到结果中:
extension String {
func group(of n: Int) -> [String] {
let chars = Array(self)
var result: [String] = []
stride(from: 0, to: chars.count, by: n).forEach {
let string = String(chars[$0..<min($0+n, chars.count)])
if let last = result.last, string.count < n {
result[result.count-1] = last + string
} else {
result.append(string)
}
}
return result
}
}
let numbers = "1234567"
let grouped = numbers.group(of: 2)
print(grouped) // ["12", "34", "567"]
答案 1 :(得分:1)
试试这个
func SplitString(stringToBeSplitted:String, By:Int) -> [String]
{
var newArray = [String]()
var newStr = String()
for char in stringToBeSplitted
{
newStr += String(char)
if newStr.count == By
{
newArray.append(newStr)
newStr = ""
}
}
return newArray
}
答案 2 :(得分:0)
var testString = "abcdefghijklmnopqrstu"
var startingPoint: Int = 0
var substringLength: Int = 1
var substringArray = [AnyHashable]()
for i in 0..<(testString.count ?? 0) / substringLength {
var substring: String = (testString as NSString).substring(with: NSRange(location: startingPoint, length: substringLength))
substringArray.append(substring)
startingPoint += substringLength
}
print("\(substringArray)")
OutPut: ( 一个, b, C, d, E, F, G, H, 一世, Ĵ, K, L, 男, N, O, p, q, R, S, T, ü )
答案 3 :(得分:0)
extension String {
func split(len: Int) -> [String] {
var currentIndex = 0
var array = [String]()
let length = self.characters.count
while currentIndex < length {
let startIndex = self.startIndex.advancedBy(currentIndex)
let endIndex = startIndex.advancedBy(len, limit: self.endIndex)
let substr = self.substringWithRange(Range(start: startIndex, end: endIndex))
array.append(substr)
currentIndex += len
}
return array
}
}
&#34; 123456789&#34; .split(2)
//输出:[&#34; 12&#34;,&#34; 34&#34;,&#34; 56&#34;,&#34; 78&#34;,&#34; 9&# 34]
答案 4 :(得分:0)
我在目标c中写了一个方法,如下所示,
-(NSMutableArray*)splitString : (NSString*)str withRange : (int)range{
NSMutableArray *arr = [[NSMutableArray alloc]init];
NSMutableString *mutableStr = [[NSMutableString alloc]initWithString:str];
int j = 0;
int counter = 0;
for (int i = 0; i < str.length; i++) {
j++;
if (range == j) {
j = 0;
if (!(i == str.length - 1)) {
[mutableStr insertString:@"$" atIndex:i+1+counter];
}
counter++;
}
}
arr = (NSMutableArray*)[mutableStr componentsSeparatedByString:@"$"];
NSLog(@"%@",arr);
return arr;
}
您可以将此方法称为
[self splitString:@"123456" withRange:2];
,结果将是,
(
12,
34,
56
)
答案 5 :(得分:0)
您也可以尝试以下代码:
var arrStr: [Substring] = []
let str = "1234567"
var i = 0
while i < str.count - 1 {
let index = str.index(str.startIndex, offsetBy: i)
//Below line gets current index and advances by 2
let substring = str[index..<str.index(index, offsetBy: 2)]
arrStr.append(substring)
i += 2
}
if str.count % 2 == 1 {
arrStr.append(str.suffix(1))
}
print(arrStr)
答案 6 :(得分:0)
这是一种愚蠢的方式,你可以考虑数据模型的规则。
var strOld = "123456"
print("The original string:\(strOld)")
strOld.insert("、", at: strOld.index(before: strOld.index(strOld.startIndex, offsetBy: 3)))
strOld.insert("、", at: strOld.index(before: strOld.index(strOld.startIndex, offsetBy: 6)))
print("After inserting:\(strOld)")
let str = strOld
let splitedArray = str.components(separatedBy: "、")
print("After the split of the array:\(splitedArray)")
let splitedArrayOther = str.split{$0 == "、"}.map(String.init)
print("After break up the array (method 2):\(splitedArrayOther)")
结果:
The original string:123456
After inserting:12、34、56
After the split of the array:["12", "34", "56"]
After break up the array (method 2):["12", "34", "56"]
答案 7 :(得分:0)
这是一个简短(简洁)的解决方案,这要归功于递归:
extension Collection {
func chunks(ofSize size: Int) -> [SubSequence] {
// replace this by `guard count >= size else { return [] }`
// if you want to omit incomplete chunks
guard !isEmpty else { return [] }
return [prefix(size)] + dropFirst(size).batches(ofSize: size)
}
}
由于Swift支持尾部调用优化,因此递归不会造成性能问题。
另外,如果在元素的前置或追加时Swift数组真的非常快(就像Objective-C一样),那么数组操作也应该很快。
这样您将获得快速且可读的代码(假设我的数组假设是正确的)。
答案 8 :(得分:0)
雨燕5
ShortDesc