Convert string with explicit escape sequence into relative character

前端 未结 5 1543
离开以前
离开以前 2020-12-06 17:13

I need a function to convert \"explicit\" escape sequences into the relative non-printable character. Es:

char str[] = \"\\\\n\";
cout << \"Line1\" <         


        
5条回答
  •  不知归路
    2020-12-06 18:02

    You can do that fairly easy, using the boost string algorithm library. For example:

    #include 
    #include 
    #include 
    
    void escape(std::string& str)
    {
      boost::replace_all(str, "\\\\", "\\");
      boost::replace_all(str, "\\t",  "\t");
      boost::replace_all(str, "\\n",  "\n");
      // ... add others here ...
    }
    
    int main()
    {
      std::string str = "This\\tis\\n \\\\a test\\n123";
    
      std::cout << str << std::endl << std::endl;
      escape(str);
      std::cout << str << std::endl;
    
      return 0;
    }
    

    This is surely not the most efficient way to do this (because it iterates the string multiple times), but it is compact and easy to understand.

    Update: As ybungalobill has pointed out, this implementation will be wrong, whenever a replacement string produces a character sequence, that a later replacement is searching for or when a replacement removes/modifies a character sequence, that should have been replaced.

    An example for the first case is "\\\\n" -> "\\n" -> "\n". When you put the "\\\\" -> "\\" replacement last (which seems to be the solution at a first glance), you get an example for the latter case "\\\\n" -> "\\\n". Obviously there is no simple solution to this problem, which makes this technique only feasible for very simple escape sequences.

    If you need a generic (and more efficient) solution, you should implement a state machine that iterates the string, as proposed by davka.

提交回复
热议问题