问题
I am using the following code to filter out line breaks, etc., and replace them with spaces. Then, I am using another line to take that double space and replace it with only one space, but it still looks like there is a double space.
What am I doing wrong?
NSString *body = [message bodyPreferringPlainText:&isPlain];
body = [body stringByReplacingOccurrencesOfString:@"\r" withString:@"\n"];
body = [body stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
body = [body stringByReplacingOccurrencesOfString:@" " withString:@" "];
http://i.stack.imgur.com/yNX6O.png
EDIT: I think I have found my problem, this only happens when the message is formatted like so:
Hello,
How are you doing?
Thanks!
But not when like this:
Hello,
How are you doing?
Thanks!
Any ideas?
回答1:
I have figured out, with the help of GoZoner, that this is the code I needed:
NSString *body = [message bodyPreferringPlainText:&isPlain];
body = [[body componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]]
componentsJoinedByString:@" "];
body = [body stringByReplacingOccurrencesOfString:@" " withString:@" "];
回答2:
I would suggest a slightly different approach. Split the string by 'whitespace' and then rebuild the string. Like this:
body = [[body componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString: " "];
The specific problem that you are having is the following. You start with:
Hello,
How are you doing?
Thanks!
Which as a string is "Hello,\r\n\r\nHow are you doing?\r\n\r\nThanks"
. You then transform, step by step as:
"Hello,\n\n\n\nHow are you doing?\n\n\n\nThanks" #\r becomes \n
"Hello, How are you doing? Thanks" #\n becomes ' ' (four of them)
"Hello, How are you doing? Thanks" #' ' becomes ' ' (four become two)
Use what I suggest, it is the best solution. If you don't like that, just replace '\r'
with ''
.
来源:https://stackoverflow.com/questions/16180313/filter-out-double-space