去除字符串中的空格

来源:互联网 发布:软件著作权登记系统 编辑:程序博客网 时间:2024/05/16 06:58

1.去掉两端的空格

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]   //stringByTrimmingCharactersInSet: 是将字符串str和集合共同的部分,从str中剪掉。

2.去掉多余的空格

NSString *str = @"    this     is a    test    .   ";      NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];  // 返回空格和tab    NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];      NSArray *parts = [str componentsSeparatedByCharactersInSet:whitespaces];      NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];      str = [filteredArray componentsJoinedByString:@" "];  // [NSCharacterSet whitespaceAndNewlineCharacterSet ]返回的是空格和tab和回车

结果:this空格is空格a空格test.

3.去掉所有空格

[str stringByReplacingOccurrencesOfString:@" " withString:@""]  
0 0
原创粉丝点击