过滤掉双倍空间

时间:2013-04-23 22:36:27

标签: iphone string sdk

我使用以下代码过滤掉换行符等,并用空格替换它们。然后,我使用另一行来获取该双倍空间并仅用一个空格替换它,但它看起来仍然有一个双重空间。

我做错了什么?

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

编辑:我认为我发现了我的问题,这只发生在邮件格式如下:

Hello,

How are you doing?

Thanks!

但不是这样的话:

Hello,
How are you doing?
Thanks!

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在GoZoner的帮助下,我发现这是我需要的代码:

NSString *body = [message bodyPreferringPlainText:&isPlain];
    body = [[body componentsSeparatedByCharactersInSet:
             [NSCharacterSet whitespaceAndNewlineCharacterSet]]
            componentsJoinedByString:@" "];
    body = [body stringByReplacingOccurrencesOfString:@"  " withString:@" "];

答案 1 :(得分:0)

我建议采用略有不同的方法。用'whitespace'拆分字符串,然后重建字符串。像这样:

body = [[body componentsSeparatedByCharactersInSet:
               [NSCharacterSet whitespaceCharacterSet]]
            componentsJoinedByString: " "];

您遇到的具体问题如下。你从:

开始
Hello,

How are you doing?

Thanks!

字符串为"Hello,\r\n\r\nHow are you doing?\r\n\r\nThanks"。然后,您逐步转换为:

  "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)

使用我的建议,这是最好的解决方案。如果您不喜欢,请将'\r'替换为''