📜  检查意图是否有额外内容 - C++ (1)

📅  最后修改于: 2023-12-03 15:26:46.396000             🧑  作者: Mango

检查意图是否有额外内容 - C++

在编写程序时,有时需要检查用户输入的意图是否包含额外的内容。这可以通过以下方式实现:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string intent = "Do something with this file";
    std::string command = "Do something with this file --extra-argument";
    
    // Split the intent and command into individual tokens
    std::vector<std::string> intentTokens;
    std::vector<std::string> commandTokens;
    
    std::string delimiter = " ";
    
    size_t pos = 0;
    std::string token;
    
    while ((pos = intent.find(delimiter)) != std::string::npos) {
        token = intent.substr(0, pos);
        intentTokens.push_back(token);
        intent.erase(0, pos + delimiter.length());
    }
    intentTokens.push_back(intent);
    
    pos = 0;
    
    while ((pos = command.find(delimiter)) != std::string::npos) {
        token = command.substr(0, pos);
        commandTokens.push_back(token);
        command.erase(0, pos + delimiter.length());
    }
    commandTokens.push_back(command);
    
    // Remove the additional content from the command
    std::vector<std::string> extraArgs;
    std::set_difference(commandTokens.begin(), commandTokens.end(),
        intentTokens.begin(), intentTokens.end(),
        std::inserter(extraArgs, extraArgs.begin()));
    
    // Determine if there is any additional content
    if (extraArgs.size() > 0) {
        std::cout << "Command contains additional content:\n";
        for (auto arg : extraArgs) {
            std::cout << "- " << arg << "\n";
        }
    } else {
        std::cout << "Command does not contain additional content.\n";
    }
    
    return 0;
}

在上面的示例中,我们将用户输入的意图和命令分成单个标记,并使用std::set_difference算法比较它们。如有必要,我们可以删除命令中的额外标记。

我们可以将此代码放入一个函数中,以方便在程序中多次使用。以下是该函数的简化版本:

#include <vector>
#include <string>
#include <algorithm>

bool has_extra_content(const std::string& intent, const std::string& command) {
    std::vector<std::string> intentTokens;
    std::vector<std::string> commandTokens;
    
    std::string delimiter = " ";
    
    size_t pos = 0;
    std::string token;
    
    while ((pos = intent.find(delimiter)) != std::string::npos) {
        token = intent.substr(0, pos);
        intentTokens.push_back(token);
        intent.erase(0, pos + delimiter.length());
    }
    intentTokens.push_back(intent);
    
    pos = 0;
    
    while ((pos = command.find(delimiter)) != std::string::npos) {
        token = command.substr(0, pos);
        commandTokens.push_back(token);
        command.erase(0, pos + delimiter.length());
    }
    commandTokens.push_back(command);
    
    std::vector<std::string> extraArgs;
    std::set_difference(commandTokens.begin(), commandTokens.end(),
        intentTokens.begin(), intentTokens.end(),
        std::inserter(extraArgs, extraArgs.begin()));
    
    return extraArgs.size() > 0;
}

此函数返回布尔值,表示命令是否包含额外的内容。