Validating multiple characters in nsstring

I have a line and I want to check for several characters in this line the following code that works fine for a single character to check for 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];
+2
source share
3 answers

UPDATE: The previous example was broken, as NSScannerit should not be used like that. Here is a much simpler 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);
+5
source

Take a look at the following method in the NSCharacterSet:

+ (id)characterSetWithCharactersInString:(NSString *)aString

You can create a character set with more than one character (hence the name character set) using this class method to create your set. The parameter is a string; each character in this string ends in a character set.

0

NSCountedSet. .

For example, from the documents:

countForObject: Returns the count associated with this object in the receiver.

- (NSUInteger)countForObject:(id)anObject

Parameters object Object to return the counter.

Return value The counter associated with anObject in the receiver, which can be considered as the number of occurrences of the object present in the receiver.

0
source

Source: https://habr.com/ru/post/1598777/


All Articles