tags:

views:

528

answers:

3

hi 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];
A: 

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.

drvdijk
+1  A: 
Nathan de Vries
Why does this method only return a character count when the character set contains 2 or more characters?If I set this:NSCharacterSet *charactersToCount = [NSCharacterSet characterSetWithCharactersInString:@"C"];I expect to get characterCount = 2 but instead, I get: "No characters found". Any ideas?
Smendrick
I've updated the previous example.
Nathan de Vries
A: 

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.

mahboudz