Filter out double space

天大地大妈咪最大 提交于 2019-12-24 09:48:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!