首页 > 代码库 > NSString去掉空格和换行失败

NSString去掉空格和换行失败

从谷歌地图接口取回数据包含回车换行符号,由于需要须把空格和换行符去掉,正常来说应该把字符串内的\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:@""];

失败截图:









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

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等方法无法替换的朋友,希望可以明示一下。