What's the best way to trim whitespace from a string in Cocoa Touch?
Asked Answered
T

3

24

I'm looking to determine whether a string value from a user input (UITextField) is "blank" if it's not nil. Checking if [textField.text isEqualToString:""] isn't quite enough because I want to avoid any blank/whitespace input (like say a few space characters).

There does seem to be an indication of a good solution for my particular problem in this StOv post.

Basically it goes something like this, but I suspect there has to (or ought to) be a better way:

NSString *strResult;
NSScanner* scanner = [NSScanner scannerWithString:textField.text];
BOOL hasValidChars = [scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] 
                                             intoString:&strResult];

// if hasValidChars == YES, we've got nonwhite space chars collected into strResult

This clearly only works for my particular circumstance, and even then it would fail if the first character was a space but the data I wanted followed. So, I realize I've been a little spoiled by Ruby, but there must be a tried and true idiom for trimming strings in Cocoa.

Aaaand the answer is already out there, my apologies:

NSString's -stringByTrimmingCharactersInSet: would do it:

Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

I'm still curious to hear if anybody has other/preferred ways of doing this.

Twin answered 23/1, 2009 at 19:58 Comment(0)
T
51

You're using whitespaceAndNewlineCharacterSet, good. But instead of using scanUpToCharactersFromSet, why not use stringByTrimmingCharactersInSet? Something like this...

strResult = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

EDIT: Didn't realize you already found stringByTrimmingCharactersInSet until after I posted this.

Thunderclap answered 23/1, 2009 at 20:22 Comment(2)
no worries, someone should get credit for the answer, and I'd feel like a tool posting it myself ;-)Twin
One question about the result string. It looks like it is an auto-released string. So it should be be released after use, right?Antiquate
W
13

What you are looking for is

[string stringByReplacingOccurrencesOfString:@" " withString:@""].

Deleting white space in the middle of a string is not called 'trimming'.

Trimming by definition works from the edges.

Willaims answered 30/9, 2010 at 20:4 Comment(0)
A
1

To make this easier on yourself and instead of making a subclass, you can modify existing Apple classes and do something like

//
// NSString+MyExtensions.h
//

@interface NSString (MyExtensions)

- (NSString *)trimmed;

@end

and the implementation

//
// NSString+MyExtensions.m
//

#import "NSString+MyExtensions.h"

@implementation NSString (MyExtensions)

- (NSString *)trimmed {
     return [self stringByTrimmingCharactersInSet:
             [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

@end

So now anywhere in your app that you use an NSString,
you can now call [@" hello world " trimmed] like below

//
// ViewController.m
//

#import "NSString+MyExtensions.h"

@implementation ViewController

- (void)viewDidLoad {

    NSString *string = @"      This is a string    ";

    NSLog(@"The original string: %@ \n The trimmed string: %@\n\n",
          string,
          [string trimmed]);

    string = @"                 ";

    if([string trimmed].length == 0)
        NSLog(@"%@", @"String is empty! :O");

}

@end

Which would print out

The original string:       This is a string    
The trimmed string: This is a string

String is empty! :O
Armidaarmiger answered 29/5, 2015 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.