drbj drbj - 1 year ago 102
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
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download