[英]What's wrong with this strings comparison function in C? How are strings compared?
昨天我在一次采訪中,要求編寫一個比較兩個字符串的函數,基本上與strcmp()的輸出相同。 我編寫了以下程序和compare()函數,但被告知錯誤。 采訪者說:“您將字符串從低字節到高字節進行比較。如果string1的較小字節較小,而較大的較高字節,則您的代碼將輸出string1小於string 2,這是錯誤的。”
我想當我們進行字符串比較時,我們從左到右比較兩個字符串,並將每對對應的字符與它們的ASCII值進行比較。 我還找到了一些strcmp()的源代碼,並嘗試了很多情況將我的結果與strcmp()的結果進行比較,所以我認為該程序是正確的。
我把程序寫在這里的采訪中。 為了進行比較,我同時打印了我編寫的函數和strcmp()的值。 我不得不說這不是很簡潔。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare (char *string1, char *string2, int length1, int length2);
int main()
{
int len1,len2;
char *str1;
char *str2;
int result;
int result1;
//Input the string1
printf("Please input the length of string1\n");
scanf("%d", &len1);
str1=malloc(sizeof(char)*len1);
printf("Please input string 1:\n");
scanf("%s",str1);
//Input the string2
printf("Please input the length of string2\n");
scanf("%d", &len2);
str2=malloc(sizeof(char)*len2);
printf("Please input string 2:\n");
scanf("%s",str2);
//Do comparison, Both compare() and strcmp() are used
result=compare(str1,str2,len1,len2);
result1=strcmp(str1,str2);
printf("\nThe result of compare() is: %d\n",result);
printf("The result of strcmp() is:%d\n",result1);
return 0;
}
int compare (char *string1, char *string2,int length1, int length2)
//If string1>string2, return1; if string1<string2, return -1; if string1=string2, return 0
{
int result=0;
// Use the shorter length to do comprison bit by bit
int length=(length1>length2)?length2:length1;
for(int i=0;i<length-1;i++)
{
if(string1[i]>string2[i])
{
result=1;
printf("%d\n",result);
break;
}
else if (string1[i]<string2[i])
{
result=-1;
printf("%d\n",result);
break;
}
}
if(result==1)
{
return 1;
}
else if (result==-1)
{
return -1;
}
else if (length1>length2)
{
return 1;
}
else if (length1<length2)
{
return -1;
}
else
{
return 0;
}
}
那么誰能告訴我程序有什么問題嗎? 您能否舉一個例子,說明compare()和strcmp()的結果不一樣?
謝謝!
您傳遞了錯誤的字符串長度,或者為str1和str2分配的內存錯誤,這會導致scanf中出現未定義的行為。
例如,內存分配是:
str2 = malloc(sizeof(char) * len2);
那么只有len2
字符可以在數組str2
(包括nul char),字符串長度可以為len2 - 1
。
我建議做類似的事情(閱讀評論):
int max_lenght = 128; // defined a constant
str1 = malloc(max_lenght);
printf("Please input string 1:\n");
fgets(str1, max_lenght, stdin);
len1 = strlen(str1); // calculate length
您不需要檢查結果值是否等於-1
返回-1,如果等於0就返回0 ...只需執行以下操作:
int result=0, i; // result is 0
for(i=0; i < length-1; i++)
{
if(string1[i] > string2[i])
{
result = 1; // result is 1
break;
}
else if (string1[i] < string2[i])
{
result = -1; // result -1
break;
}
}
return result; // return what is result is
// comparison like if(result == -1) return -1 not needed
實際上更簡單:
for(result=0, i=0; i < length-1; i++){
if(string1[i] == string2[i])
continue; // just continue until equal
if(string1[i] > string2[i])
result = 1;
else
result = -1;
break; // else break
}
return result;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.