开发者

How can I use .NET-style escape sequences in runtime values?

开发者 https://www.devze.com 2023-03-13 08:31 出处:网络
This problem comes to me when I was writing delimiter value in a 开发者_如何学编程XML config file, normally when you write a string like \"\\t\" in XML config, parser class like XDocument will automat

This problem comes to me when I was writing delimiter value in a 开发者_如何学编程XML config file, normally when you write a string like "\t" in XML config, parser class like XDocument will automatically convert it to @"\\t" so that you are getting a backslash and a 't' from the string that is parsed from the config. However, what I want is just a tab character rather than a two-character string.

So the problem turns into: given a string containing an escape sequence like "\t", how do I convert it into a one-character tab?


How about just removing the @ prefix?

Verbatim and normal string literals are ways to write strings in your source code. At runtime there is no difference between them. Then they are just plain strings.

If you want to handle escape sequences at runtime you can do something like the following:

string ReplaceEscapeSequences(string s)
{
  Contract.Requires(s != null);
  Contract.Ensures(Contract.Result<string>() != null);

  StringBuilder sb = new StringBuilder();
  for(int i = 0; i < s.Length; i++)
  {
    if(s[i] == '\\')
    {
      i++;
      if(i == s.Length)
        throw new ArgumentException("Escape sequence starting at end of string", s);
      switch(s[i])
      {
        case '\\':
          sb.Append('\\');
          break;
        case 't':
          sb.Append('\t');
          break;
        ...
      }
    }
    else sb.Append(s[i]);
  }
  return sb.ToString();
}


You can do something like this:

stringValue = stringValue.Replace("\\t", "\t");

I wrote the following method to replace a bunch of common escape character sequences.

    public static string LiteralValue(this string value)
    {
        return value
            .Replace("\\\\", "\\")
            .Replace("\\a", "\a")
            .Replace("\\b", "\b")
            .Replace("\\f", "\f")
            .Replace("\\n", "\n")
            .Replace("\\r", "\r")
            .Replace("\\t", "\t")
            .Replace("\\v", "\v")
            .Replace("\\0", "\0");
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消