1

我有一个字符串,其中包含一些带有句点和逗号的文本。我想根据逗号和句点将其转换为 NSArray。我使用这种方法根据一种条件进行分离,但是如何使用两种情况进行分离?

componentsSeparatedByString:

谢谢。

4

3 回答 3

9

您可以使用componentsSeparatedByCharactersInSet:.

例如:

NSString *str = @"1,2.3";

NSArray *arr = [str componentsSeparatedByCharactersInSet:
                [NSCharacterSet characterSetWithCharactersInString:@",."]];

请参阅NSString 类参考

于 2012-04-27T03:39:17.187 回答
5

您需要在NSCharacterSet其中创建一个逗号和一个点,并使用此方法:

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

这是一个例子:

NSArray *arr = [str componentsSeparatedByCharactersInSet:
      [NSCharacterSet characterSetWithCharactersInString:@",."]];
于 2012-04-27T03:38:16.777 回答
4
 NSString *tempTextOut = [NSString stringWithFormat:@"jdnfj,adsfsajfhkj,hasdfjhdsjkfh,hdsufhajkdsfhk"];
NSMutableArray *array = [[tempTextOut componentsSeparatedByString: @","] mutableCopy];
NSLog(@"%@",array);

>>输出1

jdnfj,
adsfsajfhkj,
hasdfjhdsjkfh,
hdsufhajkdsfhk

NSString *tempTextOut = [NSString      stringWithFormat:@"jdnfj,adsfsajfhkj,,,hasdfjhdsjkfh,,,,hdsufhajkdsfhk"];
NSMutableArray *array = [[tempTextOut componentsSeparatedByString: @",,,"] mutableCopy];
NSLog(@"%@",array);

>>输出2

 "jdnfj,adsfsajfhkj",
hasdfjhdsjkfh,
",hdsufhajkdsfhk"

希望对你有帮助..

于 2012-04-27T03:42:18.470 回答