Skip to content

Instantly share code, notes, and snippets.

@derektu
Last active December 12, 2015 09:09
Show Gist options
  • Save derektu/4749063 to your computer and use it in GitHub Desktop.
Save derektu/4749063 to your computer and use it in GitHub Desktop.
NSString extension
// NSString+StringExtension.h
//
#import <Foundation/Foundation.h>
@interface NSString (StringExtension)
// Trim off leading and trailing whitespaces
//
-(NSString*) trim;
// Trim off trailing whitespaces
//
-(NSString*) trimEnd;
// Trim off leading whitespaces
//
-(NSString*) trimStart;
// Return YES if string is ""
//
-(BOOL)isEmpty;
// Return a substring
//
-(NSString *)substringFrom:(NSUInteger)from to:(NSUInteger)to;
@end
// NSString+StringExtension.m
//
#import "NSString+StringExtension.h"
@implementation NSString (StringExtension)
- (NSString*)trim
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (NSString*)trimEnd
{
return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (NSString*)trimStart
{
return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (BOOL)isEmpty
{
return [self isEqualToString:@""];
}
- (NSString*)substringFrom:(NSUInteger)from to:(NSUInteger)to
{
NSString *rightPart = [self substringFromIndex:from];
return [rightPart substringToIndex:to - from];
}
- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet
{
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
for (; location < length; location++)
{
if (![characterSet characterIsMember:charBuffer[location]])
break;
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet
{
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
for (; length > 0; length--)
{
if (![characterSet characterIsMember:charBuffer[length - 1]])
break;
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment