c++ - const char * 测试与字符是否相等

标签 c++

如果“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/

相关文章:

c++ - 未声明类的类成员

c++ - gdb核心文件丢失

c++ - QtCreator 4.1.0 不显示 MainWindow 表单编辑器的 webengineview(QT 5.7)

c++ - 单例中的 FunktionPointerArray

C++ STL 列表计算平均值

python - 如何使用 SWIG 为 C++ 模板类创建调度包装类

c++ - Qt 在屏幕上正确放置新窗口,鼠标居中,移入屏幕

c++ - 在 C++ 中创建和使用跨平台结构

C++递归查找字符串数组中的最小元素

c++ - 在 Mac OS 上编译 Halide 的 camera_pipe 应用程序时出现问题