如果我对您的理解正确,那么您需要的是以下内容
size_t drawHangman( const std::string &word, char c )
{
static size_t wrongTries = 0;
if ( word.find( c ) != std::string::npos )
{
return ( wrongTries = 0 );
}
else
{
return ( ++wrongTries );
}
}
如果您需要重置 wrongTries,您可以使用一些任意值调用 i,例如
drawHangman( " ", ' ' );
如果您不想按照我上面显示的方式调用函数来重置 wrongTries,那么您可以通过以下方式定义它
size_t drawHangman( const std::string &word = " ", char c = ' ' )
{
static size_t wrongTries = 0;
if ( word.find( c ) != std::string::npos )
{
return ( wrongTries = 0 );
}
else
{
return ( ++wrongTries );
}
}
你可以简单地称之为
drawHangman();
重置错误尝试。
如果您需要不区分大小写的搜索,则可以使用标准算法std::find_if
。例如
#include <algorithm>
size_t drawHangman( const std::string &word, char c )
{
static size_t wrongTries = 0;
suto it = std::find_if( word.begin(), word.end(),
[=]( char t ) { return ( std::toupper( t ) == std::toupper( c ) ); } );
if ( it != word.end() )
{
return ( wrongTries = 0 );
}
else
{
return ( ++wrongTries );
}
}
另一方面,如果您需要计算字符串中不存在字符的所有情况,您可以按以下方式编写函数
int drawHangman( const std::string &word = "", char c = '\0' )
{
static int wrongTries = 0;
if ( word.empty() )
{
wrongTries = 0;
return wrongTries;
}
if ( word.find( c ) != std::string::npos )
{
return ( -wrongTries );
}
else
{
return ( ++wrongTries );
}
}
因此您可以通过以下方式检查字符串中是否存在字符
if ( drawHangman( SomeString, SomeChar ) <= 0 )
{
// the character is found in the string
}
else
{
// the character is not found in the string
}
如果您需要重置 wrongTries,您可以将该函数称为
drawHangman();