如果“toParse”中只有一个字符并且该字符是“+”或“0”,我想返回“jackpot”。最优雅的方法是什么?我试过了,但显然它不起作用,因为它出于未知原因一直返回“头奖”。
char* ParseNRZI::parse(const char* toParse){
if (toParse=="+"||toParse=="0")
return "jackpot";
}
最佳答案
使用strcmp
如果将 C 风格的指针与 char 进行比较
char* ParseNRZI::parse(const char* toParse)
{
if (strcmp(toParse, "+") == 0 ||
strcmp(toParse, "0") == 0)
{
return "jackpot";
}
return "something else";
}
或者如果您使用 std::string
你可以使用 operator==
自由地
std::string ParseNRZI::parse(const std::string& toParse)
{
if (toParse == "+" ||
toParse == "0")
{
return std::string("jackpot");
}
return std::string("something else");
}
从设计的角度来看,您正在编写一个检查函数,而不是一个真正的解析函数。然后您可以将函数重写为:
bool isJackpot(const std::string& value)
{
if (toParse == "+" ||
toParse == "0")
{
return true;
}
return false;
}
它可以简化为:
bool isJackpot(const std::string& value)
{
return value.find_first_of("0+") != std::string::npos;
}
注意:您的函数并不总是返回 char*
在所有分支中,它将在 toParse
时调用未定义的行为不是 +
或 0
.当函数返回类型不是 void
时,确保所有函数分支都返回一个值.
关于c++ - const char * 测试与字符是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18028281/