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 I am ah";
6 NSLog(@""%@" removes the space before and after the "%@"", strSource, [NSString trimWhitespace:strSource]);
7
8 strSource = @"\nKenmu I am ah\n";
9 NSLog(@""%@" removes the carriage return before and after the "%@"", strSource, [NSString trimNewline:strSource]);
10
11 strSource = @"\n Kenmu I am ah\n";
12 NSLog(@""%@" removes the space before and after the carriage return and is "%@"", strSource, [NSString trimWhitespaceAndNewline:strSource]);
13
14 strSource = @"$+Kenmu I am ah +$";
15 NSLog(@""%@" is removed before and after $ and + is followed by "%@"", 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]]; //Remove the space before and after
12 }
13 + (NSString *)trimNewline:(NSString *)val {
14 return [self trim:val trimCharacterSet:[NSCharacterSet newlineCharacterSet]]; //Remove the carriage return
15 }
16 + (NSString *)trimWhitespaceAndNewline:(NSString *)val {
17 return [self trim:val trimCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //Remove the space before and after and the carriage return
18 }
19 @end
Results:
1 2015-05-18 21:07:08.192 OCNSStringTrim[519:18080] " Kenmu I am ah wu" remove the space before and after the "Kenmu I am martial"
2 2015-05-18 21:07:08.193 OCNSStringTrim[519:18080] "\nKenmu I am ah\n" remove the carriage return before and after the "Kenmu I am ah"
3 2015-05-18 21:07:08.193 OCNSStringTrim[519:18080] "\n Kenmu I am ah wu \n" remove the space before and after the carriage return and "carriage" is "Kenmu I am martial"
4 2015-05-18 21:07:08.194 OCNSStringTrim[519:18080] "$+Kenmu I am ah wu +$" remove the before and after $ and + characters for "Kenmu I am ah"
OBJECTIVE-C syntax string NSString Remove front and back spaces or carriage returns (can be other characters of type Nscharacterset)