[英]comparing a char to a string in C
我對 C 很陌生,我想知道為什么在下面的代碼中,我與字符串單詞的每個字母進行比較的字符顯示每次都相等。 例如
如果我輸入了這個詞
蘋果
我正在“蘋果”我的函數中尋找任何重復的字符。 我將蘋果的每個字符傳遞給函數,例如 a、p、p 等。當我傳入 p 時它應該返回 1,因為它是重復的,但是,對於蘋果的每個字符,我的函數說 a == word[0 ], a == word[1] 即使“apple”的 word[1] 是 'p'。 我知道 char 是 ASCII,所以每個 char 都有一個數值,但我不確定為什么這不起作用。 也許,我在函數參數中錯誤地使用了指針 *word?
下面是我的函數 rpt_letter 的代碼:
int rpt_letter(char *word, char c)
{
int i;
int count = 0;
i = 0;
printf("This is the WORD %s\n", word);
while(count < 2)
{
if(word[i] == c)
{
count++;
printf("the count is %d\n the char is %c and the string is %c\n", count, c, word[i]);
}
i++;
}
if (count<2)
{
// printf("letter %c was not found in the array. \n", c);
return 0;
}
else
{
//printf("letter %c was found at index %d in the array.\n", c, mid);
repeats[rpt_counter] = c;
rpt_counter++;
return 1;
}
return 0;
}
以防萬一,我將包含主要方法 - 但我相信主要方法運行良好
int main(void)
{
//! showArray(list, cursors=[ia, ib, mid])
//int n = 51;
char word[51];
scanf("%s", word);
//length of string
for (n=0; word[n] != '\0'; n++); //calculate length of String
printf("Length of the string: %i\n", n);
int count = 0;
//sort words
int i;
char swap = ' ';
for(int k = 0; k < n; k++)
{
for (i=0; i<n-1; i++)
{
//if prev char bigger then next char
if (word[i] > word[i+1])
{
//make swap = prev char
swap = word[i];
//switch prev char with next char
word[i] = word[i+1];
//make next letter char
word[i+1] = swap;
}
}
}
printf("%s\n", word);
for (i=0; i<n-1; i++)
{
int rpt = rpt_letter(word, word[i]);
if(rpt == 1)
{
count++;
}
}
printf("%d", count);
return 0;
}
我嘗試了很多方法,例如使用運算符 !=,還有 <,>,但它給了我相同的結果,每個單詞 [ia] == c。
您遇到此問題是因為在您的代碼rpt_letter()
,while 循環具有終止條件count >= 2
。 現在考慮輸入apple
和字符a
。 由於a
在apple
只出現一次,遍歷整個單詞后的計數仍為 1。但循環不會終止。 因此,索引i
變得大於字符串的長度並嘗試檢查之后出現的字符。
當它a
這種方式獲得另一個a
時,循環最終終止。 您需要在循環中添加對終止空字符的檢查,以便它不會超過 string 的長度。
將 while 循環條件更改為類似 - while((count < 2) && (word[i] != '\\0'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.