C 庫 - ispunct() 函式



C 的ctypeispunct() 函式用於判斷給定字元是否為標點符號。

標點符號是指那些不是字母數字字元且不是空格字元的字元。這通常包括 !、@、#、$、%、^、&、*、(、) 等字元。

語法

以下是 ispunct() 函式的 C 庫語法 -

int ispunct(int ch);

引數

此函式接受一個引數 -

  • ch - 要檢查的字元,作為 int 傳遞。它必須可表示為無符號字元或 EOF 的值。

返回值

如果字元是標點符號,則函式返回非零值(真)。否則返回零。

示例 1:檢查字串中的多個字元

在這裡,我們計算字串“Hello, World!”中標點符號的數量,分別是 , 和 !。

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

int main() {
   char str[] = "Hello, World!";
   int count = 0;

   for (int i = 0; str[i] != '\0'; i++) {
      if (ispunct(str[i])) {
         count++;
      }
   }
   printf("The string \"%s\" contains %d punctuation characters.\n", str, count);
   return 0;
}

輸出

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

The string "Hello, World!" contains 2 punctuation characters.

示例 2:使用者輸入驗證

現在在這個程式碼中,我們檢查使用者輸入的字元是否為標點符號。

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

int main() {
   char ch;
   printf("Enter a character: ");
   scanf("%c", &ch);

   if (ispunct(ch)) {
      printf("You entered a punctuation character.\n");
   } else {
      printf("You did not enter a punctuation character.\n");
   }
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果 -

(Example input: @)
You entered a punctuation character.
廣告
© . All rights reserved.