I have an NSString
which contains a number, like 9823. Now I need to iterate though that string and print some statements based on the digit. For example, for digit 8 I should print ("A"), for digit nine: ("B") and so on. For checking I will use a switch
statement, but I don't know how to iterate through each character in the number (again, it is an NSString). In Swift
I can use for in
loop, but because NSString
isn't considered as an array in Objective-C, I can't use that here, so I wonder whether there is any alternatives to for in
in Objective-C
, which can be used with NSString
. I'm just learning Objective-C
, so I would appreciate any help.
Asked
Active
Viewed 296 times
0

Tigran Iskandaryan
- 1,371
- 2
- 14
- 41
-
You could use `rangeOf:` that's simpler to find if there is a "8" or not, but https://stackoverflow.com/questions/4158646/most-efficient-way-to-iterate-over-all-the-chars-in-an-nsstring ? – Larme Dec 20 '17 at 15:05
1 Answers
0
NSRegularExpression
would be a very good fit here:
NSString *yourString = @"Greetings SEN 5241, LUH 3417 and THX 1138.";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d*?8\\d*)"
options:kNilOptions
error:&error];
NSAssert(!error, @"%@", error);
[regex enumerateMatchesInString:yourString
options:kNilOptions
range:NSMakeRange(0, yourString.length)
usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
NSLog(@"%@", [yourString substringWithRange:result.range]);
}];
There are some very good online regular expression playgrounds (such as RegExr) which can help. Additionally, regular expressions are a skill that's useful anywhere, in any language.

jjrscott
- 1,386
- 12
- 16