문제

I have a time string that looks like this: 5:34 pm. I want to grab the 5, put it in a variable, and grab the 34 and put it in a variable. Is this possible?

Thanks in advance!

도움이 되었습니까?

해결책

NSArray *splitString = [timeString componentsSeparatedByString:@":"];
if ([splitString count] > 1 {
    NSString *hours = [splitString objectAtIndex:0];
    NSString *minutes = [splitString objectAtIndex:1];
}
else {
    //improperly formatted string
}

다른 팁

Watch out for the NSString technique listed above. If your string is missing a colon you'll crash getting objectAtIndex:1. (I'd comment on it but I lack sufficient rep.)

This should be a little more robust.

int hours, minutes;
if (2 == sscanf([timeString UTF8String], "%d:%d", &hours, &minutes))
{
    // congratulations, you did it
}
else
{
    // the string was malformed
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top