3

this is my implementation of strcmp ,

   #include <stdio.h>
   #include <string.h>

   int ft_strcmp(const char *s1, const char *s2)
   {
       while (*s1 == *s2)
       {
           if (*s1 == '\0')
              return (0);
          s1++;
          s2++;
      }
      return (*s1 - *s2);
  }

  int main()
  {
      char    s1[100] = "bon";
      char    s2[100] = "BONN";
      char    str1[100] = "bon";
      char    str2[100] = "n";
      printf("%d\n", ft_strcmp(s1, s2));
      printf("%d\n", ft_strcmp(str1, str2));
      return (0);
  }

from the book kernighan and Ritchie but i use a while loop, instead of the for, i ve tested it many times and my strcmp geaves the same results as the original strcmp, but i do not understand the results , i rode the man: "The strcmp() and strncmp() functions lexicographically compare the null-terminated strings s1 and s2." what does lexicography means ? "return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2." i understand this part but my questions are how can it come up with such results:

32
-12

s1 looks < s2 for me so how and why do i get 32 and how the calcul is made ? str1 looks > str2 for me, how and why do i get -12 and how the calcul is made. I ve compile it with the real STRCMP and i get the Same results..

last question why do i need to compare *s1 to '\0' won't it work fine without ?

thank you for your answers i m confused..

4

4 回答 4

3

1) K&R 正在比较这些字符的 ascii 值,这就是为什么你得到 32 和 -12,查看一个ascii 表,你就会明白。

2)如果你不检查 \0 ,你怎么知道字符串何时结束?那是 c 字符串终止符。

于 2015-03-15T14:27:06.987 回答
1

就 ASCII 码而言,大写字母实际上位于小写字母之前,如您在此处所见。

所以就字典顺序而言,s1被视为大于s2,因为不同的第一个字母的 ascii 值是较大的。

于 2015-03-15T14:28:08.253 回答
0

因此,我们将 *s1 与 '\0' 进行比较,以查看字符串何时结束,并使用每个字符串的第一个字符的十进制值得出结果。

于 2015-03-15T14:41:54.490 回答
0
int ft_strcmp(char *s1,char *s2)
{
    int x;

    x = 0;
    while(s1[x] != '\0' && s2[x] != '\0' && s1[x] == s2[x])
        i++;
    return (s1[x] - s2[x]);
}

通过 mokgohloa 盟友

于 2018-04-25T05:55:05.180 回答