比较不同长度的字符串,没有任何标准库

时间:2017-11-11 17:27:38

标签: c arrays string

我想编写一个函数,根据字母顺序比较不区分大小写的字符串。

char compare(char *x, char *y){
    while (*x != '\0'){
        if (tolower(*x) < tolower(*y)){
            return -1;
        }
        else if (tolower(*x) > tolower(*y)){
            return 1;
        }
        else{
            x++;
            y++;
        }
    }
return 0;
}

但是这个功能对于首字母很少的单词(例如单词和文字游戏)效果不佳。所以我试图修改它:

char compare(char *x, char *y){
if (len(*x) < len(*y)){
    while (*x != '\0'){
        if (tolower(*x) < tolower(*y)){
            return -1;
        }
        else if (tolower(*x) > tolower(*y)){
            return 1;
        }
        else{
            x++;
            y++;
        }
    }
//         all n letters are the same (case insensitive), where n is a length of x
    if (*y != '\0') return -1;
}
else {
    while (*y != '\0'){
        if (tolower(*x) < tolower(*y)){
            return -1;
        }
        else if (tolower(*x) > tolower(*y)){
            return 1;
        }
        else{
            x++;
            y`++;
        }
    }
//         all n letters are the same (case insensitive), where n is a length of y
    if (*x != '\0') return 1;
}
return 0;
}

但它没有用。如何修改此功能以使'wordplay'大于'word'?

1 个答案:

答案 0 :(得分:1)

你的第一次尝试(几乎)没问题,只需要调整你提出的问题

char compare(const char *x, const char *y){
    while ((*x != '\0') && (*y != '\0')) { // testing y for symmetry
        if (tolower(*x) < tolower(*y)){
            return -1;
        }
        else if (tolower(*x) > tolower(*y)){
            return 1;
        }
        else{
            x++;
            y++;
        }
    }
 // added conditions to handle shorter/longer strings
 if  (*x == '\0') 
  {
      if (*y == '\0')
      {
         return 0;
      }
      else
      {
         return -1;
      }
  }
  return 1;
}

我已经删除了测试的长度,添加了处理你提到的案例的逻辑。也许它不是最优化的代码,但它完成了工作(还要注意我在主循环中测试x&amp; y字符串的结尾)

我已经针对stricmp的结果进行了测试,并得到了相同的结果:

void test(const char*a,const char*b)
{
   printf("test %s %s => %d, %d\n",a,b,compare(a,b),stricmp(a,b));
}

int main(void) {
  test("abc","aBcd");
  test("abc","aBcd");
  test("abc","aBc");
  test("abcdef","abC");
  test("abcdef","cdef");

}

结果:

test abc aBcd => -1, -1
test abc aBcd => -1, -1
test abc aBc => 0, 0
test abcdef abC => 1, 1
test abcdef cdef => -1, -1