本文介绍了如何将NSString转换为NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
NSString* str = @"[90, 5, 6]";
我需要将其转换为数组
NSArray * numbers = [90, 5 , 6];
我做了很长的路:
+ (NSArray*) stringToArray:(NSString*)str
{
NSString *sep = @"[,";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *temp=[str componentsSeparatedByCharactersInSet:set];
NSMutableArray* numbers = [[NSMutableArray alloc] init];
for (NSString* s in temp) {
NSNumber *n = [NSNumber numberWithInteger:[s integerValue]];
[numbers addObject:n];
}
return numbers;
}
是否有任何简洁快捷的方式进行此类转换?
Is there any neat and quick way to do such conversion?
谢谢
推荐答案
首先从字符串中删除不需要的字符,喜欢白色空格和大括号:
First remove the unwanted characters from the string, like white spaces and braces:
NSString* str = @"[90, 5, 6]";
NSCharacterSet* characterSet = [[NSCharacterSet
characterSetWithCharactersInString:@"0123456789,"] invertedSet];
NSString* newString = [[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:@""];
您将拥有如下字符串: 90,5,6
。然后简单地使用逗号分割并转换为 NSNumber
:
You will have a string like this: 90,5,6
. Then simply split using the comma and convert to NSNumber
:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:@","];
NSMutableArray* arrayOfNumbers = [NSMutableArray arrayWithCapacity:arrayOfStrings.count];
for (NSString* string in arrayOfStrings) {
[arrayOfNumbers addObject:[NSDecimalNumber decimalNumberWithString:string]];
}
使用 NSString
来自的类别可以简化为:
Using the NSString
category from this response it can be simplified to:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:@","];
NSArray* arrayOfNumbers = [arrayOfStrings valueForKey: @"decimalNumberValue"];
这篇关于如何将NSString转换为NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!