Objective-C语法之字符串NSString去掉前后空格或回车符(可以是NSCharacterSet类型的其它字符)

main.m

 1 #import <Foundation/Foundation.h>
 2 #import "NSString+Trim.h"
 3 int main(int argc, const char * argv[]) {
 4     @autoreleasepool {
 5         NSString *strSource = @" Kenmu 我是啊武 ";
 6         NSLog(@"“%@”去掉前后空格后为“%@”", strSource, [NSString trimWhitespace:strSource]);
 7         
 8         strSource = @"\nKenmu 我是啊武\n";
 9         NSLog(@"“%@”去掉前后回车符后为“%@”", strSource, [NSString trimNewline:strSource]);
10         
11         strSource = @"\n Kenmu 我是啊武 \n";
12         NSLog(@"“%@”去掉前后空格和回车符后为“%@”", strSource, [NSString trimWhitespaceAndNewline:strSource]);
13         
14         strSource = @"$+Kenmu 我是啊武+$";
15         NSLog(@"“%@”去掉前后$和+符后为“%@”", strSource, [NSString trim:strSource trimCharacterSet:[NSCharacterSet symbolCharacterSet]]);
16     }
17     return 0;
18 }

 

NSString+Trim.h

1 #import <Foundation/Foundation.h>
2 @interface NSString (Trim)
3 + (NSString *)trim:(NSString *)val trimCharacterSet:(NSCharacterSet *)characterSet;
4 + (NSString *)trimWhitespace:(NSString *)val;
5 + (NSString *)trimNewline:(NSString *)val;
6 + (NSString *)trimWhitespaceAndNewline:(NSString *)val;
7 @end

 

NSString+Trim.m

 1 #import "NSString+Trim.h"
 2 @implementation NSString (Trim)
 3 + (NSString *)trim:(NSString *)val trimCharacterSet:(NSCharacterSet *)characterSet {
 4     NSString *returnVal = @"";
 5     if (val) {
 6         returnVal = [val stringByTrimmingCharactersInSet:characterSet];
 7     }
 8     return returnVal;
 9 }
10 + (NSString *)trimWhitespace:(NSString *)val {
11     return [self trim:val trimCharacterSet:[NSCharacterSet whitespaceCharacterSet]]; //去掉前后空格
12 }
13 + (NSString *)trimNewline:(NSString *)val {
14     return [self trim:val trimCharacterSet:[NSCharacterSet newlineCharacterSet]]; //去掉前后回车符
15 }
16 + (NSString *)trimWhitespaceAndNewline:(NSString *)val {
17     return [self trim:val trimCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去掉前后空格和回车符
18 }
19 @end

 

结果:

1 2015-05-18 21:07:08.192 OCNSStringTrim[519:18080] “ Kenmu 我是啊武 ”去掉前后空格后为“Kenmu 我是啊武”
2 2015-05-18 21:07:08.193 OCNSStringTrim[519:18080] “\nKenmu 我是啊武\n”去掉前后回车符后为“Kenmu 我是啊武”
3 2015-05-18 21:07:08.193 OCNSStringTrim[519:18080] “\n Kenmu 我是啊武 \n”去掉前后空格和回车符后为“Kenmu 我是啊武”
4 2015-05-18 21:07:08.194 OCNSStringTrim[519:18080] “$+Kenmu 我是啊武+$”去掉前后$和+符后为“Kenmu 我是啊武”

 

你可能感兴趣的:(Objective-C)