Dylan
Dylan

Reputation: 1029

Replace characters in string in C

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?

Upvotes: 3

Views: 5720

Answers (4)

wbao
wbao

Reputation: 215

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;
}

Upvotes: 1

Philip
Philip

Reputation: 5917

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 ;)

Upvotes: 0

Deepanjan Mazumdar
Deepanjan Mazumdar

Reputation: 1507

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.

Upvotes: 0

Kevin
Kevin

Reputation: 1706

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.

Upvotes: 1

Related Questions