NSString *string = @" \n I Love China ";
NSLog(@"原始字符串%@",string);
//去掉字符串两端空格
NSString *str1 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"去掉字符串两端空格%@",str1);
//去掉字符串两端空格和回车
NSString *str2 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
NSLog(@"去掉字符串两端空格和回车%@",str2);
//去掉字符串中的空格和回车
NSMutableString *mutStr = [NSMutableString stringWithString:string];
NSRange range = {0,string.length};
[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
NSRange range2 = {0,mutStr.length};
[mutStr replaceOccurrencesOfString:@"\n"withString:@""options:NSLiteralSearch range:range2];
NSLog(@"去掉字符串中的空格和回车%@",mutStr);
打印信息
2017-06-26 17:19:45.211 GCDdemo[1718:132780] 原始字符串
I Love China
2017-06-26 17:19:45.211 GCDdemo[1718:132780] 去掉字符串两端空格
I Love China
2017-06-26 17:19:45.212 GCDdemo[1718:132780] 去掉字符串两端空格和回车I Love China
2017-06-26 17:19:45.213 GCDdemo[1718:132780] 去掉字符串中的空格和回车ILoveChina