我嘗試運行這段代碼,它似乎只會檢查一個字符而不是整個字串,如果我有一個像“Adam@”這樣的長字串,有誰知道如何檢查整個字串而不是像'這樣的字符n'。
char ch;
/* Input character from user */
printf("Enter any character: ");
scanf("%c", &ch);
/* Alphabet check */
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("'%c' is alphabet.", ch);
}
else if(ch >= '0' && ch <= '9')
{
printf("'%c' is digit.", ch);
}
else
{
printf("'%c' is special character.", ch);
}
uj5u.com熱心網友回復:
C 語言沒有直接的字串概念。只有標準庫具有:按照慣例,字串表示為以空字符結尾的字符陣列。
所以你必須:
宣告一個足夠大的陣列來保存預期的字串(比如不超過 31 個字符)
char word[32]; // 31 chars 1 terminating null讀取(空白或空格分隔的)單詞,注意或不溢位陣列:
scanf("1s", word);回圈遍歷該單詞的字符:
for (int i=0; i<strlen(word); i ) { char ch = word[i]; // copy here your current code processing ch }
uj5u.com熱心網友回復:
由于您必須使用 char 陣列來存盤此字串,因此您可以輕松地遍歷此陣列。
就像 htis 一樣:
char s[100]; //string with max length 100
/* Input string from user */
printf("Enter any string: ");
scanf("%s", &s);
/* Alphabet check */
for(int i = 0; i <100; i ){
char ch = s[i];
if(ch == '\0') break; //stop iterating at end of string
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("'%c' is alphabet.", ch);
}
else if(ch >= '0' && ch <= '9')
{
printf("'%c' is digit.", ch);
}
else
{
printf("'%c' is special character.", ch);
}
}
uj5u.com熱心網友回復:
scanf("%c", &ch);
這只會讀取一個字符。要閱讀整個單詞,請使用:
char word[32]; // set size to the maximum word length you want to handle ( 1 for null termination)
scanf("1s", word);
然后使用回圈檢查單詞中的每個字符,例如:
for (int i = 0; i < 32; i ) {
if (char[i] == '\0') break;
// Check word[i]
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/407551.html
標籤:
上一篇:如何將陣列轉換為C中函式的引數?
