我NSString
从服务器收到一个。现在,我想将其拆分为所需的子字符串。如何分割字符串?
例如:
substring1:从第二个字符读取到第5个字符
substring2:从第6个字符读取10个字符。
Answers:
您还可以使用NString的componentsSeparatedByString方法将字符串按子字符串拆分。
文档中的示例:
NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];
我写了一个小方法将字符串分割成指定数量的部分。请注意,它仅支持单个分隔符。但是我认为这是拆分NSString的有效方法。
//split string into given number of parts
-(NSArray*)splitString:(NSString*)string withDelimiter:(NSString*)delimiter inParts:(int)parts{
NSMutableArray* array = [NSMutableArray array];
NSUInteger len = [string length];
unichar buffer[len+1];
//put separator in buffer
unichar separator[1];
[delimiter getCharacters:separator range:NSMakeRange(0, 1)];
[string getCharacters:buffer range:NSMakeRange(0, len)];
int startPosition = 0;
int length = 0;
for(int i = 0; i < len; i++) {
//if array is parts-1 and the character was found add it to array
if (buffer[i]==separator[0] && array.count < parts-1) {
if (length>0) {
[array addObject:[string substringWithRange:NSMakeRange(startPosition, length)]];
}
startPosition += length+1;
length = 0;
if (array.count >= parts-1) {
break;
}
}else{
length++;
}
}
//add the last part of the string to the array
[array addObject:[string substringFromIndex:startPosition]];
return array;
}