【问题标题】:Compare two chars of different strings in C比较C中不同字符串的两个字符
【发布时间】:2014-02-04 21:04:21
【问题描述】:

您好,我想比较 C 中不同字符串的两个字符,但它不起作用,请帮助我:

int main (void)
{

    string b="blue";
    int len=strlen(b);
    int numbers[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
    string letters="abcdefghijklmnopqrstuvwxyz";
    int leng=strlen(letters);
    int key [len];


    for (int i=0; i<len;i++)
    {
        for (int j=0; j<leng;j++)
        {

            if (&b[i]==&letters[j])
            {
                //The program never comes inside here 
                key[i]=numbers[j];
            }
        }

    }

    //The result should be key[]={1,11,20,4 }
}

【问题讨论】:

  • 这真的是 C++ 吗?显然std::string 在 C 中不存在...

标签: c string char compare equals


【解决方案1】:

用途:

b[i]==letters[j]

而不是

&b[i]== &letters[j]

后者比较指针值。

【讨论】:

  • ... 因为这是两个不同的对象,所以它们的指针不应该相同(它们在内存中的不同位置)。
  • 还要注意key的元素不一定是顺序赋值的;可能有未分配的元素。你可能想要一个额外的变量来计算你写给key的内容。
  • ... 和 strlen() 不应与 std::string 混合使用(只需使用 length() 成员函数代替)。您的回答没有任何问题,只是建议可以合并的其他要点以使其更完整。
  • @dvnrrs 问题被标记为 C,所以我假设 string 类似于 typedef char string[]; 而不是 std::string。
  • 我要求 OP 澄清一下,我怀疑他的意思是 C++ 而不是 C,但我不确定。
【解决方案2】:

虽然@ouah 给了你一个简短的答案(为什么你的代码不工作),你可能有兴趣注意到一个字符的 ascii 值是它的“值”,所以你可以更有效地实现你想要的

string b="blue";
int len=strlen(b);
int key [len]; // not sure what version of C allows this... compiler needs to know size of array at compile time!


for (int i=0; i<len;i++)
{
    key[i]=b[i] - 'a';
}

对于“标准 C”解决方案,您需要进行更多更改:

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

int main(void) {
  char b[] = "blue";
  int len = strlen(b);
  int *key;
  key = malloc(sizeof(b) * sizeof(int));

  for (int i=0; i<len;i++)
  {
    key[i]=b[i] - 'a';
    printf("key[%d] = %d\n", i, key[i]);
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    相关资源
    最近更新 更多