iOS开发-去除字符串中的连续空格

//把连续的空格替换成一个

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s{2,}" options:NSRegularExpressionCaseInsensitive error:&error];

NSArray *arr = [regex matchesInString:originalString options:NSMatchingReportCompletion range:NSMakeRange(0, originalString.length)];

arr = [[arr reverseObjectEnumerator] allObjects];

for (NSTextCheckingResult *str in arr) {
    originalString = [originalString stringByReplacingCharactersInRange:[str range] withString:@" "];
}

//去除空格

originalString = [originalString stringByReplacingOccurrencesOfString:@" "withString:@""];

originalString = [originalString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

你可能感兴趣的:(iOS开发-去除字符串中的连续空格)