将具有显式转义序列的字符串转换成相对字符

将具有显式转义序列的字符串转换成相对字符

本文介绍了将具有显式转义序列的字符串转换成相对字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个函数来将显式转义序列转换为相对不可打印的字符。
Es:

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

char str[] = "\\n";
cout << "Line1" << convert_esc(str) << "Line2" << endl:

会给出这个输出:

Line1

Line2

是有没有这样的功能?

推荐答案

我认为你必须自己编写这样的功能,因为转义字符是一个编译时间功能,即当您写入\\\
时,编译器将替换 \\\
序列与eol字符。生成的字符串为长度1 (不包括终止零字符)。

I think that you must write such function yourself since escape characters is a compile-time feature, i.e. when you write "\n" the compiler would replace the \n sequence with the eol character. The resulting string is of length 1 (excluding the terminating zero character).

在您的情况下,一个字符串\\ \\
长度2 (再次不包括终止零),并包含 \ n

In your case a string "\\n" is of length 2 (again excluding terminating zero) and contains \ and n.

您需要扫描字符串,遇到 \ 检查以下char。如果它是合法转义之一,您应该将其替换为相应的字符,否则跳过或将它们保持原样。

You need to scan your string and when encountering \ check the following char. if it is one of the legal escapes, you should replace both of them with the corresponding character, otherwise skip or leave them both as is.

():

string unescape(const string& s)
{
  string res;
  string::const_iterator it = s.begin();
  while (it != s.end())
  {
    char c = *it++;
    if (c == '\\' && it != s.end())
    {
      switch (*it++) {
      case '\\': c = '\\'; break;
      case 'n': c = '\n'; break;
      case 't': c = '\t'; break;
      // all other escapes
      default:
        // invalid escape sequence - skip it. alternatively you can copy it as is, throw an exception...
        continue;
      }
    }
    res += c;
  }

  return res;
}

这篇关于将具有显式转义序列的字符串转换成相对字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:40