将反斜杠字符串转换为反斜杠字符

时间:2014-10-06 20:08:24

标签: c++ string backslash string-conversion

将反斜杠字符串转换为反斜杠字符本身是否容易?

例如,我将如何完成这样的事情:

string newline = "\\n";
char n = somefunction(newline); // n == '\n'
cout << newline << n << "a new line";


/*output:
\n
a new line
*/

2 个答案:

答案 0 :(得分:1)

假设您的字符串只包含您要转换的代码:

char somefunction(std::string code)
{
   if ( code.length() != 2 )
       return /* your error code here */

   if ( code[0] != '\\' )
       return /* your error code here */

   switch(code[1]) {
       case 'n' : return '\n';
       case 't' : return '\t';
       case 'r' : return '\r';
   }
   return /* your error code here */
}

答案 1 :(得分:-1)

for (auto it = newline.begin(); it != newline.end(); ++it) {
  if ((*it) == '\\')
    newline.erase(it);
}
相关问题