44

(have searched, but not been able to find a simple solution to this one either here, or in Cocoa docs)

Q. How can I trim all leading whitespace only from an NSString? (i.e. leaving any other whitespace intact.)

Unfortunately, for my purposes, NSString's stringByTrimmingCharactersInSet method works on both leading and trailing.

Mac OS X 10.4 compatibility needed, manual GC.

tshepang
  • 12,111
  • 21
  • 91
  • 136
SirRatty
  • 2,338
  • 5
  • 25
  • 37

8 Answers8

70

This creates an NSString category to do what you need. With this, you can call NSString *newString = [mystring stringByTrimmingLeadingWhitespace]; to get a copy minus leading whitespace. (Code is untested, may require some minor debugging.)

@interface NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace;
@end

@implementation NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace {
    NSInteger i = 0;

    while ((i < [self length])
           && [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[self characterAtIndex:i]]) {
        i++;
    }
    return [self substringFromIndex:i];
}
@end
Jonathan.
  • 53,997
  • 54
  • 186
  • 290
John Franklin
  • 4,962
  • 1
  • 23
  • 27
  • Thanks very much John, and everyone who helped. If I change the NSInteger line for 10.4 compatibility, it works just great. Cheers. – SirRatty Jul 08 '10 at 06:12
  • I forgot 10.4 doesn't have NSInteger. Most of my work targets mobile devices, so it's been a while since I did anything for Tiger. I'm glad it worked! – John Franklin Jul 08 '10 at 07:19
  • This is very helpful. One typo: "idx" should be "i" in the while loop. – nont Mar 13 '12 at 17:24
  • 3
    Instead of doing your own while loop, use `NSString rangeOfCharacterFromSet:`, `NSString stringByTrimmingCharactersInSet:`, or if you need flexibility go for an `NSScanner` object or even Reg Ex. See other answers to this question (they have less up-votes at the moment). – Abhi Beckert Oct 05 '12 at 03:38
49

This is another solution using Regular Expressions (requires iOS 3.2):

NSRange range = [string rangeOfString:@"^\\s*" options:NSRegularExpressionSearch];
NSString *result = [string stringByReplacingCharactersInRange:range withString:@""];

And if you want to trim the trailing whitespaces only you can use @"\\s*$" instead.

Hejazi
  • 16,587
  • 9
  • 52
  • 67
37

This code is taking blanks.

NSString *trimmedText = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

NSLog(@"%@",trimmedText);

aybars
  • 892
  • 9
  • 9
  • 1
    This will remove both leading and trailing whitespaces and newline characters, while the question is how to remove ONLY those at the beginning.. – alasker May 27 '14 at 23:06
26

Here is a very efficient (uses CoreFoundation) way of doing it (Taken from kissxml):

- (NSString *)trimWhitespace {
    NSMutableString *mStr = [self mutableCopy];
    CFStringTrimWhitespace((CFMutableStringRef)mStr);

    NSString *result = [mStr copy];

    [mStr release];
    return [result autorelease];
}
Yosi Taguri
  • 1,388
  • 10
  • 15
21
 NSString *myText = @"       foo    ";    
 NSString *trimmedText = [myText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
 NSLog(@"old = [%@], trimmed = [%@]", myText, trimmedText);
Adam
  • 26,549
  • 8
  • 62
  • 79
Ramesh
  • 1,703
  • 18
  • 13
3

Here's what I would do, and it doesn't involve categories!

NSString* outputString = inputString;
NSRange range = [inputString rangeOfCharacterFromSet: [NSCharacterSet whitespaceCharacterSet]
    options:0];
if (range.location == 0) 
    outputString = [inputString substringFromIndex: range.location + range.length];

This is much less code.

zpasternack
  • 17,838
  • 2
  • 63
  • 81
lucius
  • 8,665
  • 3
  • 34
  • 41
0

I didn't really have much time to test this, and I'm not sure if 10.4 contains the UTF8String method for NSString, but here's how I'd do it:

NSString+Trimming.h

#import <Foundation/Foundation.h>

@interface NSString (Trimming)

-(NSString *) stringByTrimmingWhitespaceFromFront;

@end

NSString+Trimming.m

#import "NSString+Trimming.h"

@implementation NSString (Trimming)

-(NSString *) stringByTrimmingWhitespaceFromFront
{
    const char *cStringValue = [self UTF8String];

    int i;
    for (i = 0; cStringValue[i] != '\0' && isspace(cStringValue[i]); i++);

    return [self substringFromIndex:i];
}

@end

It may not be the most efficient way of doing this but it should work.

LandonSchropp
  • 10,084
  • 22
  • 86
  • 149
-6
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
NSCry
  • 1,662
  • 6
  • 23
  • 39
  • 1
    @" This string "; becomes @"Thisstring"; . The originator stated that all other whitespace needed to remain intact. – bneely Nov 22 '12 at 00:12
  • Please read the question before you post an answer. The question is about trimming a string on both sides. – codetiger Jul 11 '13 at 05:04