有很多花哨的方法可以做到这一点,但这是最易读和易于理解的方法之一(而且非常简单):
NSString *testData= @"Jim Bob Marcus Trent Mark\n\n"
"Megan Laurie Andrea Katherine\n"
"Dylan Liam Bernard\n"
"\n"
"Tim Thomas Britney Marcus";
// Remove duplicate spaces
while ([testData rangeOfString:@" "].location != NSNotFound)
testData = [testData stringByReplacingOccurrencesOfString:@" " withString:@" "];
// Remove duplicate newlines
while ([testData rangeOfString:@"\n\n"].location != NSNotFound)
testData = [testData stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];
NSLog(@"\n%@", testData);
// Results:
// Jim Bob Marcus Trent Mark
// Megan Laurie Andrea Katherine
// Dylan Liam Bernard
// Tim Thomas Britney Marcus
请注意,我从这个答案中复制了这种技术: https ://stackoverflow.com/a/9715463/937822 。
如果您喜欢此解决方案,也请对他的回答进行投票。:)
还有更有效的方法可以做到这一点。如果您正在处理大量数据并且性能不够好,那么循环各个字符并使用较低级别的 C 技术手动处理字符串可能是最简单的:
NSString *testData= @"Jim Bob Marcus Trent Mark\n\n"
"Megan Laurie Andrea Katherine\n"
"Dylan Liam Bernard\n"
"\n"
"Tim Thomas Britney Marcus";
// Create our C character arrays
const char *sourceString = [testData UTF8String];
int len = strlen(sourceString);
char *destString = malloc(len * sizeof(char));
// Remove the duplicate spaces and newlines by not copying them into the destination character array.
char prevChar = 0;
int y = 0;
for (int i = 0; i < len; i++)
{
if (sourceString[i] == ' ' && prevChar == ' ')
continue;
if (sourceString[i] == '\n' && prevChar == '\n')
continue;
destString[y++] = sourceString[i];
prevChar = sourceString[i];
}
destString[y] = '\0';
// Create the new NSString object
NSString *trimmedString = [NSString stringWithUTF8String:destString];
// Free our memory
free(destString);
NSLog(@"\n%@", trimmedString);
// Results:
// Jim Bob Marcus Trent Mark
// Megan Laurie Andrea Katherine
// Dylan Liam Bernard
// Tim Thomas Britney Marcus