C++ 中的 isspace() 函数


isspace() 函数是 ctype.h 中一个预定义函数。它指定参数是否是空格字符。有些空格字符包括空格、水平制表符、垂直制表符等。

下面是一个通过计算字符串中的空格数来实现 isspace() 函数的程序 −

示例

 实时演示

#include <iostream>
#include <ctype.h>

using namespace std;
int main() {
   char str[] = "Coding is fun";
   int i, count = 0;

   for(i=0; str[i]!='\0';i++) {
      if(isspace(str[i]))
      count++;
   }

   cout<<"Number of spaces in the string are "<<count;
   return 0;
}

输出

上述程序的输出如下 −

Number of spaces in the string are 2

在上述程序中,首先定义字符串。然后使用一个 for 循环,检查字符串中的每个字符以查看它们是否为空格字符。如果是,则 count 递增 1。最后,显示 count 的值。它显示在以下代码片段中 −

char str[] = "Coding is fun";
int i, count = 0;

for(i=0; str[i]!='\0';i++) {
   if(isspace(str[i]))
   count++;
}
cout<<"Number of spaces in the string are "<<count;

这是另一个演示 isspace() 函数的程序。它指定给定字符是否是空格字符。程序如下 −

示例

 实时演示

#include <iostream>
#include <ctype.h>

using namespace std;
int main() {
   char ch1 = 'A';
   char ch2 = ' ';
   if(isspace(ch1))
   cout<<"ch1 is a space"<<endl;

   else
   cout<<"ch1 is not a space"<<endl;
   
   if(isspace(ch2))
   cout<<"ch2 is a space"<<endl;

   else
   cout<<"ch2 is not a space"<<endl;
   return 0;
}

输出

上述程序的输出如下 −

ch1 is not a space
ch2 is a space

在上述程序中,定义了 ch1 和 ch2。然后使用 isspace() 来检查它们是否为空格字符。这部分的代码片段如下 −

char ch1 = 'A';
char ch2 = ' ';

if(isspace(ch1))
cout<<"ch1 is a space"<<endl;

else
cout<<"ch1 is not a space"<<endl;

if(isspace(ch2))
cout<<"ch2 is a space"<<endl;

else
cout<<"ch2 is not a space"<<endl;

更新于: 2020 年 6 月 25 日

超过 3K 浏览量

开启你的职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.