Search code examples
iosparsingnsstringnsscanner

Finding first letter in NSString and counting backwards


I'm new to IOS, and was looking for some guidance.

I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.

Can anyone give me some guidance on how to do that?

Example: '!!2553072 C'

and I want : '53072 '


Solution

  • There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).

    -(NSString *)getStringContent:(NSString *)input
    {
        NSString *substr = nil;
        NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
        if(singleLetter.location != NSNotFound)
        {
            NSInteger startIndex = singleLetter.location - 11;
            NSRange substringRange = NSMakeRange(start, 11);
            substr = [tester substringWithRange:substringRange];
        }
    
        return substr;
    }