gpt4 book ai didi

C : compare two character arrays

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:57 26 4
gpt4 key购买 nike

C:比较两个字符数组

这是我的rot函数

int my_rot13(int c) {
if ('a' <= tolower(c) && tolower(c) <= 'z')
return tolower(c)+13 <= 'z' ? c+13 : c-13;
return c;
}

int my_rot13cmp(char *a, char *b) {
int i;
for (i=1; i<strlen(a); i++) {
if (my_rot13(a[i]) > my_rot13(b[i])) {
return 1;
}
}
return -1;
}

这应该输出 1 因为D 将是解码字符中的 QW 将是解码字符中的 J且 Q > J

printf("%d \n", my_rot13cmp("\0D\n", "\0W\n"));

但这一直给我 -1

比较这两个字符的正确方法是什么?

最佳答案

您的字符串中有一个嵌入的 0 字符:

 my_rot13cmp("\0D\n", "\0W\n");

这将导致 my_rot13cmp 中的 strlen(a) 返回 0 - 因为 nul 字符表示字符串的结尾。

删除字符串中的那些\0,并在 i=0 处开始循环

关于C : compare two character arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com