2012-07-10 167 views
1

我試圖用這個函數比較兩個字符串,不區分大小寫。常量字符串不區分大小寫比較

int strcasecmp(const char *x1, const char *x2); 

我有複製件正確的,可區分大小寫的部分是給我帶來些麻煩爲const是一個常量,因此只讀取,使得這些失敗:

*x1 = (tolower(*x1)); // toupper would suffice as well, I just chose tolower 
*x2 = (tolower(*x2)); // likewise here 

兩個字符必須保持const ,否則我認爲這將工作... 所以我的問題:有沒有辦法忽略大寫,同時保持char -strings const

+2

那麼你爲什麼不只是使用一個臨時要存儲的值(tolower(* x))? – Marcus 2012-07-10 02:09:59

+0

將數據複製到非常量字符數組中,將所有字符轉換爲小寫字母。 – 2012-07-10 02:10:00

+0

@Marcus我不允許將* x1或* x2更改爲除const char – user1513475 2012-07-10 02:13:21

回答

2

你可以使用一個臨時char變量:

char c1 = tolower(*x1); 
char c2 = tolower(*x2); 

if (c1 == c2) 
... 
+0

雖然這是同樣的問題,因爲您不能將任何內容分配給只讀位置(* x1和* x2)。 – user1513475 2012-07-10 02:18:39

+0

它們被分配給局部變量。這是隻讀嗎? – Mysticial 2012-07-10 02:19:18

+0

@ user1513475:該代碼分配給本地非const char'變量'c1'和'c2'。沒有違反常量在那裏。 – 2012-07-10 02:19:31

2

當然 - 你可以的tolower比較結果就在if聲明:

while (*x1 && *x2 && tolower(*x1) == tolower(*x2)) { 
    x1++; 
    x2++; 
} 
return tolower(*x1)-tolower(*x2); 
+2

當字符不同時,你通常不會返回0 – 2012-07-10 02:17:54

+1

@JonathanLeffler你是對的,我忘了。 – dasblinkenlight 2012-07-10 02:22:16

+0

輕微:可以簡化爲'* x1 && tolower(* x1)== tolower(* x2)'。 – chux 2015-04-25 20:00:17

相關問題