我必须创建一个简单的函数来显示预定义字符数组中的空格数。 这是我的代码:(请忽略第一部分,只有最后部分和空白功能)
#include <iostream>
#include <conio.h>
using namespace std;
int whitespaces(char[]);
void main(){
char a[] = "Array of characters for test\n"; //Simple array of characters
cout << "\n This is a test : " << a;
char b[] = "\n\t Another array of character for test\n"; //Simple array with some escape sequences, \t and \n
cout << "\n This is a test for usage of escape sequences : " << b;
char c[] = "T E S T\n"; //Simple array with 8 characters and whitespaces
cout << "\n Last test for whitespaces : "<<c;
int ws = whitespaces(c);
cout << "\n Number of whitespaces for the last array of characters is : "<<ws;
_getch();
}
int whitespaces(char c[]){
int count = 0;
for (int n = 0; n <= sizeof(c); n++) {
if (c[n] == ' '){
count++;
}
}
return(count);
}
使用Visual Studio express
答案 0 :(得分:3)
如果您想要计算所有空格字符(不仅仅是空格字符),您可以使用以下内容:
std::string::size_type countWs( std::string const& str )
{
return std::count_if( std::begin(str), std::end(str),
[] (unsigned char c) {return std::isspace(c);} );
}
或者,或者,
std::size_t countWs( char const* str )
{
std::size_t c = 0;
while (*str)
c += !!std::isspace((unsigned char)*str++);
return c;
}
Demo。至于unsigned char
的演员表,this question可能值得一看。
答案 1 :(得分:1)
您必须使用标头std::strlen
中声明的标准C函数<cstring>
而不是sizeof
运算符,因为通过值传递给函数的数组会隐式转换为指向其第一个元素的指针。空白字符也不是唯一的空格字符。您应该使用标题std::isspace
中声明的标准函数std::isblank
或<cctype>
所以函数看起来像
#include <cstring>
#include <cctype>
//...
int whitespaces( const char c[] )
{
int count = 0;
size_t n = std::strlen( c );
for ( size_t i = 0; i < n; i++ )
{
if ( std::isspace( c[i] ) ) ++count;
}
return ( count );
}
另一种方法是使用存储字符串的字符数组的特性,它们具有终止零。
在这种情况下,函数可以定义为
#include <cstring>
#include <cctype>
//...
int whitespaces( const char c[] )
{
int count = 0;
while ( *c )
{
if ( std::isspace( *c++ ) ) ++count;
}
return ( count );
}
另请注意,可以使用标准算法std::count
和std::count_if
代替您的功能。