码迷,mamicode.com
首页 > 其他好文 > 详细

NSString去掉空格和换行失败

时间:2014-05-21 06:54:08      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   c   code   ext   

从谷歌地图接口取回数据包含回车换行符号,由于需要须把空格和换行符去掉,正常来说应该把字符串内的\n替换就可以了,后来试了一下不行。百度了一下,有人说换行应该是\r\n,也有人说需要换成\\n,众说纷纭,全部试过均告失败:

    NSString *temp = [[NSString alloc]initWithData:xmlData encoding:NSUTF8StringEncoding];
    [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    [temp stringByReplacingOccurrencesOfString:@"\\n" withString:@""];
    
    [temp stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    [temp stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@""];
    
    [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    [temp stringByReplacingOccurrencesOfString:@"\\r" withString:@""];

    [temp stringByReplacingOccurrencesOfString:@"\t" withString:@""];

失败截图:

bubuko.com,布布扣


bubuko.com,布布扣


bubuko.com,布布扣


bubuko.com,布布扣


经过一番折腾,终于找到了以下方法:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   
    // Strange New lines:
    //  Next Line, U+0085
    //  Form Feed, U+000C
    //  Line Separator, U+2028
    //  Paragraph Separator, U+2029
   
    // Scanner
    NSScanner *scanner = [[NSScanner alloc] initWithString:content];
    [scanner setCharactersToBeSkipped:nil];
    NSMutableString *result = [[NSMutableString alloc] init];
    NSString *temp;
    NSCharacterSet*newLineAndWhitespaceCharacters = [ NSCharacterSet newlineCharacterSet];
    // Scan
    while (![scanner isAtEnd]) {
       
        // Get non new line or whitespace characters
        temp = nil;
        [scanner scanUpToCharactersFromSet:newLineAndWhitespaceCharacters intoString:&temp];
        if (temp) [result appendString:temp];
       
        // Replace with a space
        if ([scanner scanCharactersFromSet:newLineAndWhitespaceCharacters intoString:NULL]) {
            if (result.length > 0 && ![scanner isAtEnd]) // Dont append space to beginning or end of result
                [result appendString:@" "];
        }
    }
   
    // Cleanup
    [scanner release];
   
    // Return
    NSString *retString = [[NSString stringWithString:result] retain];
    [result release];
   
    // Drain
    [pool drain];

content是需要处理的字符串,retString是结果字符串,其它不用变,直接考到需要用的地方就行。

ps:有知道\n等方法无法替换的朋友,希望可以明示一下。


NSString去掉空格和换行失败,布布扣,bubuko.com

NSString去掉空格和换行失败

标签:style   blog   class   c   code   ext   

原文地址:http://blog.csdn.net/lvxiangan/article/details/26367527

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!