Reputation: 1
Hi I want to compare two chars of different strings in C and it's not working, help me please:
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 }
}
Upvotes: 0
Views: 114
Reputation: 1
#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!");
}
The compare_two_strings(const char* text, const char* text2)
XOR's two values, checks if they are equal, and if they are it's OR'ed to the evaluate variable and then it advances to the next character.
It does this until it reaches the end of the string, then it'll leave the do while
loop and return the evaluate value.
Upvotes: 0
Reputation: 46435
Whil @ouah gave you the short answer (why your code is not working), you might be interested in noting that the ascii value of a character is its "value", so you can achieve what you wanted more efficiently with
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';
}
For a "standard C" solution, you need a couple more changes:
#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]);
}
}
Upvotes: 0
Reputation: 145919
Use:
b[i]==letters[j]
instead of
&b[i]== &letters[j]
The latter compares pointer values.
Upvotes: 3