簡體   English   中英

從另一個數組填充C中的char數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM