Anh
Anh

Reputation: 6533

Get the number of white spaces at line beginning

I tried the following implementation:

NSString *string = @"    Test";
NSString *spaces = @"";

NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:&spaces];

The number of whitespaces should be [spaces length]. However, all tests I tried always return 0.

Any ideas?

Upvotes: 2

Views: 127

Answers (1)

Costique
Costique

Reputation: 23722

Use setCharactersToBeSkipped:. The docs say,

The default set of characters to skip is the whitespace and newline character set.

So it just silently skips the whitespace prefix.

There is another way to do it:

NSUInteger prefixLength = [string rangeOfCharacterFromSet: 
    [NSCharacterSet whitespaceCharacterSet]];

Upvotes: 3

Related Questions