Search code examples
cstringsplitansi-c

ANSI C splitting string


Hey there! I'm stuck on an ANSI C problem which I think should be pretty trivial (it is at least in any modern language :/).

The (temporary) goal of my script is to split a string (array of char) of 6 characters ("123:45") which represents a timestamp minutes:seconds (for audio files so it's ok to have 120 minutes) into just the minutes and just the seconds.

I tried several approaches - a general one with looking for the ":" and a hardcoded one just splitting the string by indices but none seem to work.

void _splitstr ( char *instr, int index, char *outstr ) {
char temp[3]; 
int i; 
int strl = strlen ( instr );
if ( index == 0 ) {
    for ( i = 0; i < 3; ++i ) {
        if ( temp[i] != '\0' ) {
            temp[i] = instr[i];
        }
    }
} else if ( index == 1 ) {
    for ( i = 6; i > 3; i-- ) {
            temp[i] = instr[i];
        }
    }
strcpy ( outstr, temp );
}

Another "funny" thing is that the string length of an char[3] is 6 or 9 and never actually 3. What's wrong with that?


Solution

  • How about using sscanf(). As simple as it can get.

        char time[] = "123:45";
        int minutes, seconds;
    
        sscanf(time, "%d:%d", &minutes, &seconds);
    

    This works best if you can be sure that time string syntax is always valid. Otherwise you must add check for that. On success, sscanf function returns the number of items succesfully read so it's pretty easy to detect errors too.

    Working example: http://ideone.com/vVoBI