C# @“” how do i insert a tab?

后端 未结 12 1110
南笙
南笙 2021-01-17 08:02

Recently i found out i can write in a \" by writing two \" ex @\"abc\"\"def\". I find the @ string literal useful. But how do i write in a tab or n

相关标签:
12条回答
  • 2021-01-17 08:24

    When you are using the @ modifier, you are using something called a verbatim string literal.

    What this means is that anything you put in between the Opening and closing quotes will be used in the string.

    This includes Carraige Return, Line Feed, Tab and etc.

    Short answer: Just press tab.

    One caveat, though. Your IDE may decide to insert spaces instead of a tab character, so you may be better off using concatenation.

    0 讨论(0)
  • 2021-01-17 08:25

    Just write a tab or a newline in your string. @"" string literals recognise every character as it is written in the code file. On the contrary, escape sequences don't work.

    0 讨论(0)
  • 2021-01-17 08:26

    That quote escape sequence ("") is the only "escape" that works in verbatim string literals. All other escapes only work in regular string literals.

    As a workaround you may use something ugly like this:

    string.Format(@"Foo{0}Bar", "\t");
    

    or include an actual tab character in the string. That should also work with regular string literals, but whitespace, especially tabs, usually doesn't survive different text editors well :-)

    For newlines it's arguably much easier:

    @"Foo
    Bar";
    
    0 讨论(0)
  • 2021-01-17 08:30

    I don't know why nobody suggested nowaday to insert {"\t"} in your interpolation string, to me it's better than having to use string format.

    this works: $@"Foo{"\t"}Bar"; or concatenating strings

    0 讨论(0)
  • 2021-01-17 08:34

    If you are starting to need "special" characters within your string then maybe you should be using a normal string "" and escaping them using \ rather than using the @"".

    What sort of data are you storing in the string? What reason do you have for needing it in a @""?

    0 讨论(0)
  • 2021-01-17 08:38

    Once you start a string with @ you can put anything in between, also tabs or newlines:

    string test = @"test
    
    bla
    
    bjkl";
    

    the above string will contain the 4 newlines.

    0 讨论(0)
提交回复
热议问题