簡體   English   中英

比較 C 中不同字符串的兩個字符

[英]Compare two chars of different strings in C

嗨,我想比較 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] = %d\n", 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 的兩個值,檢查它們是否相等,如果相等,則對評估變量進行“或”運算,然后前進到下一個字符。

它會這樣做,直到它到達字符串的末尾,然后它會離開do while循環並返回評估值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM