2017-11-11 42 views
1

我想写一个函数,它根据字母顺序比较字符串不区分大小写。没有任何标准库比较不同长度的字符串

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; 
} 

但它没有工作。我怎样才能修改这个功能,使'文字游戏'会比'文字'更大?

+0

你不能用'stricmp'吧? –

+0

存在打印错误,而不是++和b ++写入x ++&y ++以及len(* x)如何工作。 – achal

+0

@ Jean-FrançoisFabre不是我不能,我只是不想 – jakes

回答

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 & 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