4thSpace
4thSpace

Reputation: 44312

Count of chars in NSString or NSMutableString?

I've tried this

NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString: myString];
[myCharSet count];

But get a warning that NSCharacterSet may not respond to count. This is for desktop apps and not iPhone, which I think the above code works with.

Upvotes: 26

Views: 43861

Answers (3)

Saiprabhakar
Saiprabhakar

Reputation: 85

NSString *string = @"0̄ 😄";
__block NSUInteger count = 0;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByComposedCharacterSequences
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                            count++;
                        }];
NSLog(@"%ld %ld", (long)count, (long)[string length]);

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 6618

I might be missing something here, but what's wrong with simply doing:

NSUInteger characterCount = [myString length];

To just get the number of characters in a string, I don't see any reason to mess around with NSCharacterSet.

Upvotes: 86

That should not work on the iPhone either, as NSCharacterSet is not a subclass of NSSet on either platform.

If you really need to get a count why not subclass NSSet, add the value, then have a method that returns that as an NSCharacterSet on demand for use in anything that needs a character set?

Upvotes: 0

Related Questions