首页 > 解决方案 > 如何在 C 中将类型为 AA:BB:CC:DD:EE:FF 的字符串转换为 0xaabbccddeeff?

问题描述

输入:AA:BB:CC:DD:EE:FF 预期输出:0xaabbccddeeff。输入:AA:BB:65:F0:E4:D4 预期输出:0xaabb65f0e4d4

      char arr[20]="AA:BB:CC:DD:EE:FF";
      char t[20]="0x";   
      char *token=strtok(arr[i], ":");
      while(token !=NULL){
      printf("%s\n", token);
      token = strtok(NULL, ":");
      strcat(t, token);
        }
printf("The modified string is %s\n", t);

我看到了分段错误。

标签: cstring

解决方案


您正在尝试strcat使用 null 令牌进行决赛。在拨打电话之前尝试移动您的条件以检查strcat

#include <ctype.h>
#include <stdio.h>
#include <string.h>

void lower(char *c) {
    for (; *c = tolower(*c); *c++);
}

int main() {
    char s[] = "AA:BB:CC:DD:EE:FF";
    char t[15] = "0x";
    char *token = strtok(s, ":");

    if (token) {
        lower(token);
        strcat(t, token);

        while (token = strtok(NULL, ":")) {
            lower(token);
            strcat(t, token);
        }
    }

    printf("The modified string is %s\n", t);
}

输出:

The modified string is 0xaabbccddeeff

推荐阅读