简体   繁体   中英

How can I get an integer value from NSString in an iPhone application?

NSString * str=[zoneDict objectForKey:@"name"];
NSLog(@"==========string zone::==========%@",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";

How can I get the 3:00 value from the above string?

 NSString *str = @"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
 NSRange endRange = [str rangeOfString:@")"];
 NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
 NSRange separatorRange = [timeString rangeOfString:@":"];
 NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
 NSLog(@"Hour:%d",hourInt);

Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict ? For example you could store NSTimeZone instances instead.

If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.

If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.

I like to use -[NSString componentsSeparatedByString]:

NSString *str = @"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:@")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:@"-"].location == NSNotFound) {
    NSArray *temp2 = [temp1 componentsSeparatedByString:@"+"];
    NSString *temp3 = [temp2 objectAtIndex:1];
    NSLog(@"Your String - %@", temp3);
}
else {
    NSArray *temp2 = [temp1 componentsSeparatedByString:@"-"];
    NSString *temp3 = [temp2 objectAtIndex:1];
    NSLog(@"Your String - %@", temp3);
}

Output:

Your String - 3:00

Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM