marciokoko
marciokoko

Reputation: 4986

How properly extract substrings from an NSString without hardcoding positions?

I have this string returning:

"Monday thru Friday 8:00 AM - 7:30 PM"

I need to eliminate the mon-fri stuff in order to get this:

"8:00AM - 7:30PM"

And then I need to split it into opening time and closing time in order to determine if its open or not:

"8:00AM" && "7:30PM"

But there are a lot of stores and they have different opening and closing times, so I cant just extract 6 characters from 8 or anything like that.

So far I decided to go this route:

NSRange startRange = [storeTime.text rangeOfString:@"-"];

NSString *openString = [storeTime.text substringWithRange:NSMakeRange(16, startRange.location-17)];

NSString *closeString = [storeTime.text substringWithRange:NSMakeRange(startRange.location+2, storeTime.text.length-(startRange.location+2))];

But it just seems like i could break because of the hardcoded start at 16 and it makes me wonder if it could break anywhere else. Any better ideas on how to achieve this?

Upvotes: 1

Views: 248

Answers (3)

user529758
user529758

Reputation:

If you know the text before the time interval is always in the format <someday> thru <someday>, then you can find the index of the first numerical character (digit), and get a substring from that index.

Then, split the time strings on @" - " using the componentsSeparatedByString: method.

Example:

NSString *s = @"monday thru sunday, 0:00 - 23:59";

NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
int idx = [s rangeOfChatacterFromSet:digits].location;
NSString *timeStr = [s substringFromIndex:idx];

NSArray *timeStrings = [timeStr componentsSeparatedByString:@" - "];

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

You can use NSRegularExpression to grab the two time strings out of a string:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
     regularExpressionWithPattern:@"\\d{1,2}:\\d{2} (AM|PM)"
                          options:NSRegularExpressionCaseInsensitive
                            error:&error];
NSString *str = @"Monday thru Friday 8:00 AM - 7:30 PM";
NSArray *m = [regex matchesInString:str
                            options:0
                              range:NSMakeRange(0, str.length)];

Upvotes: 8

C0D3
C0D3

Reputation: 6559

How about first go by replacing occurrences of some strings.

So use the [string stringByReplacingOccurrencesOfString:@"Monday" withString: @""];

remove all the days and probably the "thru" string.

Then you're left with the hours. Don't forget to watch for space characters.

Hope this helps.

Upvotes: 0

Related Questions