Reputation: 709
i have a string and i want to check for the multiple characters in this string the following code i working fine for one character how to check for the multiple characters.
NSString *yourString = @"ABCCDEDRFFED"; // For example
NSScanner *scanner = [NSScanner scannerWithString:yourString];
NSCharacterSet *charactersToCount = @"C" // For example
NSString *charactersFromString;
if (!([scanner scanCharactersFromSet:charactersToCount intoString:&charactersFromString])) {
// No characters found
NSLog(@"No characters found");
}
NSInteger characterCount = [charactersFromString length];
Upvotes: 2
Views: 7550
Reputation: 39376
Also look up NSCountedSet. It can help you keep count of multiple instances of the same character.
For example, from the docs:
countForObject: Returns the count associated with a given object in the receiver.
- (NSUInteger)countForObject:(id)anObject
Parameters anObject The object for which to return the count.
Return Value The count associated with anObject in the receiver, which can be thought of as the number of occurrences of anObject present in the receiver.
Upvotes: 0
Reputation: 5554
Have a look at the following method in NSCharacterSet:
+ (id)characterSetWithCharactersInString:(NSString *)aString
You can create a character set with more than one character (hence the name character set), by using that class method to create your set. The parameter is a string, every character in that string will end up in the character set.
Upvotes: 0
Reputation: 15511
UPDATE: The previous example was broken, as NSScanner
should not be used like that. Here's a much more straight-forward example:
NSString* string = @"ABCCDEDRFFED";
NSCharacterSet* characters = [NSCharacterSet characterSetWithCharactersInString:@"ABC"];
NSUInteger characterCount;
NSUInteger i;
for (i = 0; i < [yourString length]; i++) {
unichar character = [yourString characterAtIndex:i];
if ([characters characterIsMember:character]) characterCount++;
}
NSLog(@"Total characters = %d", characterCount);
Upvotes: 6