[英]How to realize strcmp function of string.h in C
我試圖實現C中“ string.h”庫中的strcmp
函數。這是我做的:
int myStrCmp(char str1[], int len1, char str2[], int len2)
{
int i = 0;
int stop = 0;
int cmp = 0;
for (i = 0; i < len1 && !stop; i++)
{
if (str1[i] == str2[i])
{
cmp = 0;
}
else if (str1[i] > str2[i])
{
cmp = -1; // gives 1 if string 1 will be appear first in dictionary.
stop = 1; // stops the loop.
}
else
{
cmp = 1;
stop = 1;
}
}
return cmp;
}
一切都很好,但是某些情況下無法輸入字符串。 舉個例子:
str1 = "ab";
str2 = "abcd";
我該如何解決?
我假設len1
和len2
分別是str1
和str2
的長度。
您未在代碼中使用len2
,這會導致邏輯錯誤,並可能導致崩潰(分段錯誤)。
按照您的代碼,解決方案可能是:
int myStrCmp(char str1[], int len1, char str2[], int len2)
{
int i = 0;
int stop = 0;
int cmp = 0;
for (i = 0; i < len1 && i < len2 && !stop; i++)
{
if (str1[i] > str2[i])
{
cmp = -1; // gives 1 if string 1 will be appear first in dictionary.
stop = 1; // stops the loop.
}
else if (str1[i] < str[i]
{
cmp = 1;
stop = 1;
}
}
if (!stop && len1 != len2)
{
if (str[i] == '\0')
{
cmp = -1;
}
else
{
cmp = 1;
}
}
return cmp;
}
然后,即使此代碼有效,它的樣式也很差(並且性能很差)。 我邀請您看一下Apple對strcmp函數的實現:
int strcmp(const char *s1, const char *s2)
{
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}
https://opensource.apple.com/source/Libc/Libc-262/ppc/gen/strcmp.c
首先,這不是strcmp
工作方式,也不是它返回的值。 盡管大多數實現都會為您提供-1、0和1,但是ISO標准對此進行了說明:
strcmp函數返回一個大於,等於或小於零的整數,因此s1指向的字符串大於,等於或小於s2指向的字符串。
這意味着它不必總是為-1、0和1。 您可以期望任何整數。 這也使實現也很簡單。
int mystrcmp(const char *s1, const char *s2)
{
int diff;
while(1)
{
diff = *s1 - *s2;
if(*s1 == '\0' || *s2 == '\0')
{
break;
}
s1 ++;
s2 ++;
}
return diff;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.