【问题标题】:Problem removing backslash characters on std::string删除 std::string 上的反斜杠字符时出现问题
【发布时间】:2019-08-30 14:44:19
【问题描述】:

我正在尝试执行反序列化 JSON 消息的 CMD 命令。

当我反序列化消息时,我将值存储在一个值为"tzutil /s \"Romance Standard Time_dstoff\""std::string 变量中:

当我收到带有浮动引号参数的命令(例如"tzutil /s "Romance Standard Time_dstoff"")时,我想删除反斜杠字符('\')。

std::string command = "tzutil /s \"Romance Standard Time_dstoff\""; //Problem
system(command.c_str());

有什么办法吗?

我将不胜感激。

【问题讨论】:

  • 您的意思是将所有出现的 \ 字符替换为其他内容,或者您​​想用引号替换它们?您的问题建议后者,而示例建议前者。
  • 你怎么看反斜杠字符?在打印或调试器中?您可能会发现它们实际上并不存在......
  • 我假装替换/删除所有出现的 '\' 以使用带引号的参数。我已经更新了我的帖子。
  • @FantasticMrFox 我在调试模式下看到它
  • 请注意,std::string command = "tzutil /s \"Romance Standard Time_dstoff\"" 中没有斜线。我知道您的真实字符串确实如此,但示例不正确。

标签: c++ string cmd command


【解决方案1】:

如果你想删除所有出现的字符,那么你可以使用

#include <algorithm>

str.erase(std::remove(str.begin(), str.end(), char_to_remove), str.end());

如果您想用另一个字符替换它们,请尝试

#include <algorithm>

std::replace(str.begin(), str.end(), old_char, new_char); 

【讨论】:

  • 这也将删除任何有效的反斜杠如果这对 OP 来说不是问题那么好吧,否则请参阅下面的答案。
【解决方案2】:

这是我在 C++ 中为我自己的一个项目创建的用于替换子字符串的函数。

std::string
Replace(std::string str,
    const std::string& oldStr,
    const std::string& newStr)
{

    size_t index = str.find(oldStr);
    while(index != str.npos)
    {
        str = str.substr(0, index) +
            newStr + str.substr(index + oldStr.size());
        index = str.find(oldStr, index + newStr.size());
    }
    return str;
}

int main(){
    std::string command = GetCommandFromJsonSource();
    command = Replace(command, "\\\"", "\""); // unescape only double quotes
}

【讨论】:

    【解决方案3】:

    虽然你的程序的源代码中确实包含,但由文字表示的字符串不包含任何反斜杠,如以下示例中的demonstrated

    std::string command = "tzutil /s \"Romance Standard Time_dstoff\""; //Problem
    std::cout << command;
    
    // output:
    tzutil /s "Romance Standard Time_dstoff"
    

    因此,没有什么可以从字符串中删除。

    反斜杠是转义字符。 \" 是一个转义序列,表示单个字符,即双引号。这是一种在字符串文字中键入双引号字符而不将该引号解释为字符串结尾的方法。


    要将反斜杠写入字符串文字,您可以使用反斜杠对其进行转义。以下字符串确实包含反斜杠:"tzutil /s \\"Romance Standard Time_dstoff\\""。在这种情况下,可以像这样删除所有反斜杠:

    command.erase(std::remove(command.begin(), command.end(), '\\'), command.end());
    

    但是,简单地删除角色的所有实例可能并不明智。如果您的字符串包含转义序列,那么您可能应该做的是取消转义它们。这有点复杂。您不想删除所有反斜杠,而是将\" 替换为",将\\ 替换为\,将\n 替换为换行符等等。

    【讨论】:

    • 你知道有什么方法可以取消引号中的'\'字符吗?提前致谢
    【解决方案4】:

    您可以使用 std::quoted 来转换字符串文字。

    #include <iomanip> // -> std::quoted
    #include <iostream>
    #include <sstream>
    
    int main() {
        std::istringstream s("\"Hello world\\n\"");
        std::string hello;
        s >> std::quoted(hello);
        std::cout << std::quoted(s) << ": " << s;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 2015-03-28
      • 1970-01-01
      相关资源
      最近更新 更多