C 庫 - isspace() 函式



C 庫的 isspace() 函式檢查傳遞的字元是否為空格字元。

此函式是 C 標準庫的一部分,包含在 <ctype.h> 標頭檔案中。

標準空格字元包括:

' '   (0x20)	space (SPC)
'\t'	(0x09)	horizontal tab (TAB)
'\n'	(0x0a)	newline (LF)
'\v'	(0x0b)	vertical tab (VT)
'\f'	(0x0c)	feed (FF)
'\r'	(0x0d)	carriage return (CR)

語法

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

int isspace(int c);

引數

此函式接受單個引數:

  • c − 要檢查的字元,作為 int 型別傳遞。c 的值應可表示為無符號字元或等於 EOF 的值。

返回值

如果字元是空格字元,則 isspace(int c) 函式返回非零值 (true)。否則,它返回零 (false)。isspace 檢查的空格字元包括:

  • 空格 (' ')
  • 換頁符 ('\f')
  • 換行符 ('\n')
  • 回車符 ('\r')
  • 水平製表符 ('\t')
  • 垂直製表符 ('\v')

示例 1:檢查不同的輸入是否為空格

使用 isspace() 函式檢查字元 't'、數字 '1' 和空格 '' 是否被識別為空格。

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

int main () {
   int var1 = 't';
   int var2 = '1';
   int var3 = ' ';

   if( isspace(var1) ) {
      printf("var1 = |%c| is a white-space character\n", var1 );
   } else {
      printf("var1 = |%c| is not a white-space character\n", var1 );
   }
   
   if( isspace(var2) ) {
      printf("var2 = |%c| is a white-space character\n", var2 );
   } else {
      printf("var2 = |%c| is not a white-space character\n", var2 );
   }
   
   if( isspace(var3) ) {
      printf("var3 = |%c| is a white-space character\n", var3 );
   } else {
      printf("var3 = |%c| is not a white-space character\n", var3 );
   }
   
   return(0);
}

輸出

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

var1 = |t| is not a white-space character
var2 = |1| is not a white-space character
var3 = | | is a white-space character

示例 2:換行符

此示例檢查換行符 ('\n') 是否為空格字元。由於它是空格字元,因此函式返回 true。

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

int main() {
   char ch = '\n';
   if (isspace(ch)) {
      printf("The character is a whitespace character.\n");
   } else {
      printf("The character is not a whitespace character.\n");
   }
   return 0;
}

輸出

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

The character is a whitespace character.
廣告