3

I have a char array in string of the format <item1>:<item2>:<item3> what is the best way to break it down so that I can print the different items separately? Should I just loop through the array, or is there some string function that can help?

2
  • 2
    You would benefit from reading any beginner C book, or even K&R Commented Sep 6, 2012 at 2:52
  • check out sscanf() or strtok() or do it your implementation isn't hard.. Commented Sep 6, 2012 at 3:25

4 Answers 4

1

I would use the sscanf function

char * str = "i1:i2:i3";
char a[10];
char b[10];
char c[10];
sscanf(str, "%s:%s:%s", a, b, c);

This is not secure as it is vulnerable to a buffer overflow. In Windows, there is sscanf_s as a security hack.

Sign up to request clarification or add additional context in comments.

Comments

1

You can try strtok: here is some sample code to get the sub string which is separated by , - or |

#include <stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
char  buf1[64]={'a', 'a', 'a', ',' , ',', 'b', 'b', 'b', '-', 'c','e', '|', 'a','b', };
/* Establish string and get the first token: */
char* token = strtok( buf1, ",-|");
while( token != NULL )
    {
/* While there are tokens in "string" */
        printf( "%s ", token );
/* Get next token: */
        token = strtok( NULL, ",-|");
    }
return 0;
}

2 Comments

-1, it's a really bad idea to run strtok() on a character pointer initialized from a string literal. The literal is read only, but strtok() modifies it. This could easily crash.
thanks for the suggestion. I just wrote the sample quickly but not consider this problem. Thanks.
0

strtok is the best bet, would like to add 2 things here:

1) strtok modifies/manipulates your original string and strips it out of the delimiters, and

2) if you have a multithreaded program, you could be better off using strtok_r which is the thread-safe/re-entrant version.

Comments

0

Simply iterate over the string and everytime you hit ':', print whatever has been read since the last occurrence of ':'.

#define DELIM ':'


char *start, *end;

start = end = buf1;

while (*end) {
    switch (*end) {
        case DELIM:
            *end = '\0';
            puts(start);
            start = end+1;
            *end = DELIM;
            break;
        case '\0':
            puts(start);
            goto cleanup;
            break;
    }
    end++;
}

cleanup:
// ...and get rid of gotos ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.