C 庫 - isalnum() 函式



C 的ctypeisalnum()函式用於檢查給定字元是否為字母數字字元,這意味著它是字母(大寫或小寫)或數字。

為了使用isalnum()函式,我們必須包含包含該函式的標頭檔案<ctype.h>。

語法

以下是isalnum()函式的 C 庫語法:

int isalnum(int c);

引數

此函式接受單個引數:

  • c − 此引數表示要檢查的字元。它作為 int 傳遞,但預期為可表示為無符號字元或 EOF 值的字元。

返回值

以下是返回值:

  • 如果字元是字母數字字元,則函式返回非零值(true)。

  • 如果字元不是字母數字字元,則返回 0(false)。

示例 1:檢查字元是否為字母數字字元

在此示例中,使用isalnum()函式檢查字元 a。由於a是字母,因此該函式返回非零值,表明它是字母數字字元。

#include <stdio.h>
#include <ctype.h>

int main() {
   char ch = 'a';

   if (isalnum(ch)) {
      printf("The character '%c' is alphanumeric.\n", ch);
   } else {
      printf("The character '%c' is not alphanumeric.\n", ch);
   }
   return 0;
}

輸出

以上程式碼產生以下結果:

The character 'a' is alphanumeric.

示例 2:檢查特殊字元

現在,檢查特殊字元@。由於它既不是字母也不是數字,isalnum 函式返回 0,表明@不是字母數字字元。

#include <stdio.h>
#include <ctype.h>

int main() {
   char ch = '@';

   if (isalnum(ch)) {
      printf("The character '%c' is alphanumeric.\n", ch);
   } else {
      printf("The character '%c' is not alphanumeric.\n", ch);
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

The character '@' is not alphanumeric.
廣告