嗨,我想比较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 }
}
使用:
b[i]==letters[j]
而不是
&b[i]== &letters[j]
后者比较指针值。
而 @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] = %dn", i, key[i]);
}
}
#include <stdio.h>
int compare_two_strings(const char* text, const char* text2){
int evaluate = 0;
do {
evaluate |= *text ^ *text2++;
} while (*text++);
return !(int)evaluate;
}
int main(void)
{
const char* text = "Hello";
const char* text2 = "Hello";
if (compare_two_strings(text, text2))
printf("These strings are the same!");
else printf("These strings are not the game!");
}
compare_two_strings(const char* text, const char* text2)
xor的两个值,检查它们是否相等,如果它们是评估变量,则它是" evalition to to the the contriable"。
它执行此操作,直到到达字符串的末端,然后将do while
循环留下并返回评估值。