将带有显式转义序列的字符串转换为相对字符 [英] Convert string with explicit escape sequence into relative character

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

问题描述

我需要一个函数来将显式转义序列转换为相对的不可打印字符。
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

有没有任何函数这样做?

Is there any function that does this?

推荐答案

我认为你必须自己写这样的函数,因为转义符是一个< - 时间特征,即当您写\\\
时,编译器将替换 \\\
序列与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.

您需要扫描您的字符串,遇到 \ 检查以下字符。如果它是法律转义之一,则应该用相应的字符替换它们,否则跳过或保留它们两者。

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.

http://ideone.com/BvcDE ):

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;
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆