Split string into parts

∥☆過路亽.° 提交于 2019-12-22 00:23:41

问题


I want to split NSString into array with fixed-length parts. How can i do this?

I searched about it, but i only find componentSeparatedByString method, but nothing more. It's also can be done manually, but is there a faster way to do this ?


回答1:


Depends what you mean by "faster" - if it is processor performance you refer to, I'd guess that it is hard to beat substringWithRange:, but for robust, easy coding of a problem like this, regular expressions can actually come in quite handy.

Here's one that can be used to divide a string into 10-char chunks, allowing the last chunk to be of less than 10 chars:

NSString *pattern = @".{1,10}";

Unfortunately, the Cocoa implementation of the regex machinery is less elegant, but simple enough to use:

NSString *string = @"I want to split NSString into array with fixed-length parts. How can i do this?";

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: pattern options: 0 error: &error];

NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];

NSMutableArray *result = [NSMutableArray array];                            
for (NSTextCheckingResult *match in matches) {
    [result addObject: [string substringWithRange: match.range]];
}



回答2:


Break the string into a sequence of NSRanges and then try using NSString's substringWithRange: method.




回答3:


You can split a string in different ways. One way is to split by spaces(or any character):

NSString *string = @"Hello World Obj C is Awesome";

NSArray *words = [string componentsSeparatedByString:@" "];

You can also split at exact points in a string:

NSString *word = [string substringWithRange:NSMakeRange(startPoint, FIXED_LENGTH)];

Simply put it in a loop for a fixed length and save to Mutable Array:

NSMutableArray *words = [NSMutableArray array];
for (int i = 0; i < [string length]; i++) {
    NSString *word = [string substringWithRange:NSMakeRange(i, FIXED_LENGTH)]; //you may want to make #define
    [array addObject:word];
}

Hope this helps.



来源:https://stackoverflow.com/questions/18795440/split-string-into-parts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!