[英]C : compare two character arrays
C:比較兩個字符數組
這是我的爛函數
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將在解碼字符中為Q W將在解碼字符中為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
開始循環
strlen尋找\\0
符號來確定字符串長度,您的字符串具有此特殊符號,因此strlen將不起作用,您可以使用以下幾種變體:
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如果您知道所有字符串都以\\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.