Grab numbers after a colon?
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!
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
}
NSArray *splitString = [timeString componentsSeparatedByString:@":"];
if ([splitString count] > 1 {
NSString *hours = [splitString objectAtIndex:0];
NSString *minutes = [splitString objectAtIndex:1];
}
else {
//improperly formatted string
}
精彩评论