Question

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 '

Was it helpful?

Solution 2

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;
}

OTHER TIPS

You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b

The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:

NSError *error;
NSString *example = @"!!2553072      C";
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"(.{11})\\b[A-Z]\\b"
                              options:NSRegularExpressionCaseInsensitive
                              error:&error];

if(!regex)
{
    //handle error
}

NSTextCheckingResult *match = [regex firstMatchInString:example
                                                options:0
                                                  range:NSMakeRange(0, [example length])];
if(match)
{
    NSLog(@"match: %@", [example substringWithRange:[match rangeAtIndex:1]]);
}

You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):

- (NSString *)parseString:(NSString *)myString {
    NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
    NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
    assert(components.count > 0);
    NSString *prefix = components[0]; // assuming relatively new Xcode
    return [prefix substringFromIndex:(prefix.length - 11)];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top