drbj drbj - 4 months ago 17
Objective-C Question

How to loop through an NSString and get a Substring?

I need to get a Substring from a NSString. I need to get the substring after

-
if it is followed by
E
until the next
-


For example, I have this string A-BB-CD-EF_10AW-ZWE_EG

I need to get the EF_10AW. Any idea on how can I iterate through an NSString and get a substring dynamically?

Answer

If your string contains multiple string that starts with E and ends with - than you must have one solution that can find all those strings. For such solution please refer below code:

NSString *str = @"A-BB-CD-EF_10AW-ZWE_EG";

NSArray *compArray = [str componentsSeparatedByString:@"-"];

NSMutableArray *arrayStartWithE = [NSMutableArray array];

for (int i = 0; i < [compArray count]; i++) {
    if ([[compArray objectAtIndex:i] hasPrefix:@"E"]) {
        [arrayStartWithE addObject:[compArray objectAtIndex:i]];
    }
}

Here arraystartWithE will give you all those type of string. Hope this might help you.

Comments