I am trying to copy content from one char
array to another char
array and below is my code,
char dest[100]; //destination array
char content[100]; //Which will be "11,22,33,44,55" - source array
//Split source array with comma delimiter
char *ch ;
ch = strtok(content, ",");
while (ch != NULL) {
printf("%s\n", ch); //prints each entry seperated by comma
ch = strtok(NULL, " ,");
//Code to copy content to dest ?
}
i want to populate dest
char array with below content,
dest[0] = 11 dest[1] = 22 dest[2] = 33 dest[3] = 44 dest[4] = 55
I have tried below with no luck,
memcpy(dest, ch, 1);
strcpy(dest,ch);
How can i do this?
EDIT : The source content is alpha-numerical (eg) 11,2F,3A,BB,E1 is alos possible
Try this:
int i = 0;
while (ch != NULL) {
printf("%s\n", ch);
dest[i++] = ch[0];
dest[i++] = ch[1];
ch = strtok(NULL, " ,");
}
assuming that ch
has always two characters to copy.
As far as I understand you have to consider hex representations, which can be done by using strtol with base 16 (the OP gave input "11,2F,3A,BB,E1" as example):
int i = 0;
char *ch = strtok(content, ",");
while (ch != NULL) {
printf("%s\n", ch); //prints each entry seperated by comma
dest[i++] = (char)strtol(ch, NULL, 16); // number will be 11, 22, 33 etc.
ch = strtok(NULL, ",");
}
instead of strtok, content
could be parsed using sscanf. %2hhX
will scan two hex characters and store the result in a char
. ,
will scan any whitespace and a comma. %n
will capture the number of characters processed by the scan to add to ch
to parse the next field in content
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
int main( void) {
char dest[SIZE]; //destination array
char content[SIZE] = "11,22,33,44 , 55,C,2F,3A,BB,E1";
char *ch = content;
int span = -1;
int each = 0;
while ( 1 == sscanf ( ch, "%2hhX ,%n", &dest[each], &span)) {
printf ( "%hhX\n", dest[each]);
if ( span == -1) {//failed to scan a comma
break;
}
ch += span;//advance ch to next field in content
span = -1;//reset span
each++;
if ( each >= SIZE) {
break;
}
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.