【问题标题】:Create a special character in a .txt file using C#使用 C# 在 .txt 文件中创建特殊字符
【发布时间】:2019-06-14 13:28:17
【问题描述】:

在创建 .txt 文件时,我必须在字符串中呈现一个特殊字符。特殊字符的代码是 "\x0B"。但是我们我尝试将它连接到一个字符串中,它给我的文本是原样的。你能告诉如何使用上面的代码呈现特殊字符吗?

 String totalText = totalText + @"\x0B"+ @"Text seperated with the character";
 File.WriteAllText(path + createFileName + ".txt", totalText);

【问题讨论】:

  • 帮助我们帮助您 - 分享您的代码
  • 完成,添加使用的代码
  • char c = '\x0B';

标签: c# console


【解决方案1】:

删除不必要的逐字字符串文字,使用Path.Combine:

string totalText = "Some text";
char c = '\x0B';
string textSeparatedWithCharacter = "Text seperated with the character";

totalText = $"{totalText}{c}{textSeparatedWithCharacter}";

// Or
//totalText = string.Format("{0}{1}{2}", totalText, c, textSeparatedWithCharacter);

File.WriteAllText(Path.Combine(path, createFileName + ".txt"), totalText);

【讨论】:

    【解决方案2】:

    您正在使用verbatim string literal,方法是在您的字符串前面加上一个“@”。这意味着除了使用"" 解析为" 的双引号外,没有任何内容被转义。

    这行得通吗?

    String totalText = totalText + "\x0B"+ @"Text seperated with the character";
    File.WriteAllText(path + createFileName + ".txt", totalText);
    

    【讨论】:

    • "\x0B" 应该是'\x0B'
    • string totalText = totalText + ... 应该会失败,因为您使用了未分配的局部变量。即使它会编译它也没有意义,因为它没有任何价值。
    • @fubo:在字符串连接中,将一个操作数设为char 并没有真正意义,因为它也可以是string。 sn-p 也取自问题,提问者很可能有更多关于该 sn-p 的代码,这对问题并不重要。
    • @Joey 是不是 OP 未能提供 Minimal, Complete, and Verifiable example
    • @fubo: »特殊字符的代码是...«(强调我的)。老实说,这对于使用类似 C 编程语言一段时间的任何人来说都是非常清楚和可以理解的。是的,源代码中有四个字符。不,这并不意味着应该将这四个字符写入文件。您是否在抱怨 \n 在源代码中是两个字符,但在内存中也只有一个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2020-01-12
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多