iOS 字符串 去除空格

NSString *str = @" this is a test . ";

去掉两端的空格

str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

去掉多余的空格
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"]; NSArray *parts = [str componentsSeparatedByCharactersInSet:whitespaces]; NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings]; str = [filteredArray componentsJoinedByString:@" "];
去掉所有空格

str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];

posted @ 2022-04-15 14:11  brave-sailor  阅读(1323)  评论(0编辑  收藏  举报