[英]Populate a char array in C from another array
我试图将内容从一个char
数组复制到另一个char
数组,下面是我的代码,
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 ?
}
我想用下面的内容填充dest
char数组,
dest [0] = 11 dest [1] = 22 dest [2] = 33 dest [3] = 44 dest [4] = 55
我试过下面没有运气,
memcpy(dest, ch, 1);
strcpy(dest,ch);
我怎样才能做到这一点?
编辑 :源内容是字母数字(例如)11,2F,3A,BB,E1也是可能的
尝试这个:
int i = 0;
while (ch != NULL) {
printf("%s\n", ch);
dest[i++] = ch[0];
dest[i++] = ch[1];
ch = strtok(NULL, " ,");
}
假设ch
总是要复制两个字符。
据我所知,你必须考虑十六进制表示,这可以通过使用带有基数16的strtol来完成(OP给出输入“11,2F,3A,BB,E1”作为例子):
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, ",");
}
而不是strtok,可以使用sscanf解析content
。 %2hhX
将扫描两个十六进制字符并将结果存储在char
。 ,
将扫描任何空格和逗号。 %n
将捕获扫描处理的字符数,以添加到ch
以解析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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.