There are lots of fancy ways to do this, but this is one of the most readable and easy to understand ways (as well as being pretty easy):
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
Note that I copied this technique from this answer: https://stackoverflow.com/a/9715463/937822.
Please up-vote his answer as well if you like this solution. :)
There are also more efficient ways to do this. If you are processing a large amount of data and the performance isn't good enough, then it would probably be easiest to loop through the individual characters and process the strings manually using lower level C techniques:
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