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.