首页 > 代码库 > 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等方法无法替换的朋友,希望可以明示一下。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。