簡體   English   中英

檢查 C 中字符串中的任何特殊字符

[英]Check any special characters in a string in C

我嘗試運行這段代碼,它似乎只會檢查一個字符而不是整個字符串,如果我有一個像“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);
    }****
scanf("%c", &ch);

這只會讀取一個字符。 要閱讀整個單詞,請使用:

char word[32]; // set size to the maximum word length you want to handle (+1 for null termination)
scanf("%31s", word);

然后使用循環檢查單詞中的每個字符,例如:

for (int i = 0; i < 32; i++) {
    if (char[i] == 0) break;
    // Check word[i]
    ...
}

C 語言沒有字符串的直接概念。 只有標准庫具有:按照慣例,字符串表示為 null 終止的字符數組。

所以你必須:

  1. 聲明一個足夠大的數組來保存預期的字符串(比如不超過 31 個字符)

     char word[32]; // 31 chars + 1 terminating null
  2. 讀取(空白或空格分隔的)單詞,注意或不溢出數組:

     scanf("%31s", word);
  3. 循環遍歷該單詞的字符:

     for (int i=0; i<strlen(word); i++) { char ch = word[i]; // copy here your current code processing ch }

由於您必須使用 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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM