c++ - 如何简化 C++ bool 比较

标签 c++ qt

我正在尝试找到一种方法来简化 bool 值的比较情况。目前,只有三个(如下所示),但我要添加第 4 个选项,这变得非常乏味。

bracketFirstIndex = message.indexOf('[');
mentionFirstIndex = message.indexOf('@');
urlFirstIndex = message.indexOf(urlStarter);

bool startsWithBracket = (bracketFirstIndex != -1);
bool startsWithAtSymbol = (mentionFirstIndex != -1);
bool startsWithUrl = (urlFirstIndex != -1);     

if (!startsWithBracket)
{
    if (!startsWithAtSymbol)
    {
        if (!startsWithUrl)
        {
            // No brackets, mentions, or urls. Send message as normal
            cursor.insertText(message);
            break;
        }
        else
        {
            // There's a URL, lets begin!
            index = urlFirstIndex;
        }
    }
    else
    {
        if (!startsWithUrl)
        {
            // There's an @ symbol, lets begin!
            index = mentionFirstIndex;
        }
        else
        {
            // There's both an @ symbol and URL, pick the first one... lets begin!
            index = std::min(urlFirstIndex, mentionFirstIndex);
        }
    }
}
else
{
    if (!startsWithAtSymbol) 
    {
        // There's a [, look down!
        index = bracketFirstIndex;
    }
    else
    {
        // There's both a [ and @, pick the first one... look down!
        index = std::min(bracketFirstIndex, mentionFirstIndex);
    }

    if (startsWithUrl)
    {
        // If there's a URL, pick the first one... then lets begin!
        // Otherwise, just "lets begin!"
        index = std::min(index, urlFirstIndex);
    }
}

是否有更好/更简单的方法来比较多个 bool 值,或者我是否被困在这种格式中,我应该尝试在适当的位置挤入第 4 个选项?

最佳答案

某些类型的文本处理相当普遍,对于这些,您应该强烈考虑使用现有的库。例如,如果您正在处理的文本使用 markdown语法,请考虑使用现有的库将 markdown 解析为结构化格式以供您解释。

如果这完全是自定义解析,那么有几个选项:

  • 用于非常简单的文本处理(比如预期的单个字符串 采用几种格式之一或包含一段预期格式的子文本),请使用 regular expressions .在 C++ 中,RE2库为匹配和提取 usign 正则表达式提供了非常强大的支持。

  • 对于更复杂的文本处理,例如跨越多行或具有多种内容/语法的数据,请考虑使用现有的词法分析器和解析器生成器。 FlexBison是根据语法自动生成用于解析文本的逻辑的常用工具(一起使用)。

  • 您可以像现在一样手动编写自己的解析逻辑。

如果您采用后一种方法,有几种方法可以简化事情:

  1. 将“词法分析”(将输入分解为标记)和“解析”(解释一系列标记)分成不同的阶段。

  2. 定义一个“Token”类和一个相应的层次结构,表示可以出现在您的语法中的符号类型(例如 RawText、Keyword、AtMention 等)

  3. 创建一个或多个枚举来表示您的解析逻辑可能处于的状态。

  4. 将您的词法分析和解析逻辑实现为一个状态机,该状态机在给定当前状态和下一个标记或字母的情况下转换状态。构建从 (state, token type) 到 next_state 或从 (state, token type) 到 handler_function 的映射可以帮助您简化结构。

关于c++ - 如何简化 C++ bool 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363243/

相关文章:

python - 将 QTableWidget 单元格链接到网页

c++ - Qt - 简单循环的执行速度逐渐变慢

linux - Qt 在终端上运行 shell

c# - 使用命令列表解析自定义文件

c++ - 使用唯一的指针调用函数会使我的程序崩溃

c++ - 使用C++在OpenGL中纹理3d多边形

c++ - 从 Main 方法调用函数

c++ - 通过系统变量设置QT基目录

qt - 服务器 QTcpSocket "breaks"太快了,客户端没有收到所有数据,知道为什么吗?

使用现代编译器编译的 C++ 项目,但链接到过时的 libstdc++