【问题标题】:Comparing chars one by one in a character array with strcmp [duplicate]用strcmp逐个比较字符数组中的字符[重复]
【发布时间】:2021-06-23 00:04:44
【问题描述】:

我正在编写一个 c++ 脚本,它使用 strcmp() 一个一个地比较两个字符串的字符。 我写了这段代码:

        char test1[1];
        char test2[1];
        test1[0]=str1[i];  //str1 is a char array
        test2[0]=str2[i];  //str2 is a char array
        int result=strcmp(test1,test2); 

但如果我打印 test1 或 test2 我会遇到两个字符。 例如,如果 str1='a' 的第一个索引那么 test1 是“aa”,但我不知道为什么? 请帮忙。

【问题讨论】:

  • strcmp() 需要一个 C 风格的以空字符结尾的字符串。 test1[1] 没有空间容纳角色和终结者。
  • strcmp 用于比较 NUL 终止的 C 字符串而不是单个字符。要比较字符,只需使用 == 就像 str1[i] == str2[i]

标签: c++ strcmp


【解决方案1】:

strcmp() 采用 null-terminated 字符串,但您的 char[] 数组都不是 null-terminated。

char test1[2]; // <-- increase this!
char test2[2]; // <-- increase this!
test1[0] = str1[i];
test1[1] = '\0'; // <-- add this!
test2[0] = str2[i];
test2[1] = '\0'; // <-- add this!
int result = strcmp(test1, test2); 

否则,您可以使用strncmp() 代替,它不需要空终止符,因此不需要char[] 数组,例如:

char test1 = str1[i];
char test2 = str2[i];
int result = strncmp(&test1, &test2, 1);

或者简单地说:

int result = strncmp(&str1[i], &str2[i], 1);
// or:
// int result = strncmp(str1+i, str2+i, 1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多