Search code examples
iosobjective-cnsstringsubstringnsrange

How to split strings into substring start with some characters in ios


I am stuck in finding the solution of splitting the string into substrings. I need some proper logic in which I need to read string starting with some character and it should contain at least 17 characters.

e.g. "43 01 08 43 13 01 18 FD 48 6B D1 43 01 22 02 01 02 02 F1 48 6B D1 43 02 03 03 51 03 52 75 48 6B D1 43 03 53 11 08 15 52 9D 48 6B D1 43 16 14 16 32 00 00"

For Above string , I need to split in into "43 01 08 43 13 01 18" "43 01 22 02 01 02 02" "43 02 03 03 51 03 52" "43 03 53 11 08 15 52" "43 16 14 16 32 00 00"

So On... I mean I need to get the position of "43" ,then from its index i Need to read 20 characters (Including space) and reject the characters until the next "43" appears (BOLD characters as mentioned above). Thanks in advance .. :)


Solution

  • I would just use rangeOfString: to locate the next 43, take the 20 characters from there on with substringWithRange:, and start over with the remaining substring (substringFromIndex:).

    NSString *str = @"43 01 08 43 13 01 18 FD 48 6B D1 43 01 22 02 01 02 02 F1 48 6B D1 43 02 03 03 51 03 52 75 48 6B D1 43 03 53 11 08 15 52 9D 48 6B D1 43 16 14 16 32 00 00";
    NSMutableArray *substrings = [NSMutableArray array];
    NSRange range = { .length = 20 };
    while ((range.location = [str rangeOfString:@"43"].location) != NSNotFound
           && str.length >= range.length + range.location) {
        [substrings addObject:[str substringWithRange:range]];
        str = [str substringFromIndex:range.location + range.length];
    }