Erik
Erik

Reputation: 2530

Detecting whitespaces

How do I detect whitespaces in objective-c? I've tried this:

if ([myString isEqualToString:@" ") {
// Log it
NSLog(@"match");
}

but it doesn't fire, what am I doing wrong here?

Thanks! Erik

Upvotes: 1

Views: 85

Answers (2)

Goppinath
Goppinath

Reputation: 10739

You can achieve it by:

if ([myString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location != NSNotFound) {

    NSLog(@"Whitespace found");

} else {

    NSLog(@"Whitespace not found");
}

Instead of [NSCharacterSet whitespaceCharacterSet] you can use [NSCharacterSet whitespaceAndNewlineCharacterSet] to detect newline too.

Apple's documentation says whitespace includes space and tab

A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).

hope it will help you.

Upvotes: 4

Rajesh
Rajesh

Reputation: 960

You can do like this

if([myString rangeOfString:@" "].location != NSNotFound)
{
     NSLog(@"match");           
}

Upvotes: 0

Related Questions