[英]C : compare two character arrays
C : compare two character arrays C:比较两个字符数组
Here's my rot function 这是我的烂函数
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;
}
And this should output 1 because D will be Q in decoded character W will be J in decoded character And Q > J 这应该输出1,因为D将在解码字符中为Q W将在解码字符中为J并且Q> J
printf("%d \n", my_rot13cmp("\0D\n", "\0W\n"));
But this keeps giving me -1 但这一直给我-1
What is the correct way to compare these two characters? 比较这两个字符的正确方法是什么?
You have an embedded 0 character in your strings: 您的字符串中包含一个嵌入式0字符:
my_rot13cmp("\0D\n", "\0W\n");
This will cause strlen(a)
inside my_rot13cmp to return 0 - since a nul character means the end of the string. 这将导致my_rot13cmp内的
strlen(a)
返回0-因为nul字符表示字符串的结尾。
Remove those \\0 in your strings, and start the loop at i=0
删除字符串中的\\ 0,然后从
i=0
开始循环
strlen looks for \\0
symbol to determine string length, your strings has this special symbol, so strlen will not work, you have several variants: strlen寻找
\\0
符号来确定字符串长度,您的字符串具有此特殊符号,因此strlen将不起作用,您可以使用以下几种变体:
1 have separate argument for length, like: 1有单独的长度参数,例如:
int my_rot13cmp(char *a, char *b, size_t aLength, size_t bLength)
{
if (aLength > bLength)
return 1;
if (aLength < bLength)
return -1;
for (int i=0; i<aLength; i++)
if (my_rot13(a[i]) > my_rot13(b[i]))
return 1;
else if (my_rot13(a[i]) < my_rot13(b[i]))
return -1;
return 0;
}
2 if you know that all your strings just started with \\0
and do not contain it until the end (asciiz null terminator must be), you can go with this solution: 2如果您知道所有字符串都以
\\0
开头并且直到结尾都没有包含(必须为asciiz null终止符),则可以采用以下解决方案:
int my_rot13cmp(char *a, char *b)
{
a++; b++; // skips first \0 symbol
for (int i=0; i<strlen(a); i++) // note: what will be if A is longer than B?
if (my_rot13(a[i]) > my_rot13(b[i]))
return 1;
else if (my_rot13(a[i]) < my_rot13(b[i]))
return -1;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.