ios将字符串"5小时10分钟"转换为整数小时和分钟

Mee*_*ade 2 objective-c nsstring ios

我正在尝试从字符串"5小时10分钟"获取整数变量中的小时和分钟.可以任何人给我解决方案.

NSString *duration =@"5 hours 10 min";

int hours = 5
int min = 10
Run Code Online (Sandbox Code Playgroud)

Nim*_*ekh 7

请尝试以下代码来检索int值.

@try {
    NSString *myString = @"5 hours 10 min";
    NSArray *myWords = [myString componentsSeparatedByCharactersInSet:
                        [NSCharacterSet characterSetWithCharactersInString:@" "]
                        ];
    int hoursValue = 0, minuteValue = 0;
    hoursValue = [[myWords objectAtIndex:0] intValue];
    if([myWords count] > 2) {
        minuteValue = [[myWords objectAtIndex:2] intValue];
    }

    NSLog(@"hours %d and Minute %d",hoursValue,minuteValue);
 }
 @catch (NSException * e) {
    NSLog(@"Exception: %@", e);
 }
Run Code Online (Sandbox Code Playgroud)