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;