如何拆分NSString保留特定的标点符号?

时间:2019-09-06 19:38:18

标签: objective-c nsstring nsarray delimiter nscharacterset

我需要将句子拆分为特定的标点符号,但要保留这些标点符号。

我正在这样做:

NSCharacterSet *delimeter = [NSCharacterSet characterSetWithCharactersInString:@"***"];

sentence  = [sentence  stringByReplacingOccurrencesOfString:@"," withString:@",***"];
sentence  = [sentence  stringByReplacingOccurrencesOfString:@"!" withString:@"!***"];
sentence  = [sentence  stringByReplacingOccurrencesOfString:@"?" withString:@"?***"];
sentence  = [sentence  stringByReplacingOccurrencesOfString:@"." withString:@".***"];
sentence  = [sentence  stringByReplacingOccurrencesOfString:@":" withString:@":***"];
sentence  = [sentence  stringByReplacingOccurrencesOfString:@";" withString:@";***"];

NSArray *sentenceArray = [sentence  componentsSeparatedByCharactersInSet: delimeter];
NSMutableArray *finalSentenceArray = [sentenceArray mutableCopy];
[finalSentenceArray removeObject:@""];

但是这样做,我有需要删除的空字符串。什么是更有效的方法?

谢谢!

0 个答案:

没有答案