How to use \ in a string in C #

I want to use \ in a string, e.g.

string str="abc\xyz"; 

But that gives me an error.

I also tried

 string str="abc\\xyz"; 

But still it does not work. Can anyone help me out?

+4
source share
8 answers
 public class Program { static void Main(string[] args) { string str = "abc\\xyz"; Console.WriteLine(str); } } 

It works great. It prints abc\xyz .

+2
source

You can either escape from the symbol, for example:

 string str="abc\\xyz"; 

or use a string string literal as follows:

 string str=@ "abc\xyz"; 

So your second example should work.

See here for more details.

+13
source
 string str="abc\\xyz"; 

This should usually work. An alternative is:

 string str = @"abc\xyz"; 
+5
source

Well, the last one ( "abc\\xyz" ) will certainly result in a backslash in the string - or you could use a literal string literal:

 string str = @"abc\xyz"; 

Note that if you use the debugger to view your lines, it often (always?) "Runs away" from them for you, so you will see "abc\\xyz" . This can cause confusion. Either look at the characters individually, or print a line on the console.

You did not say how it "does not work" - could you give more detailed information? If this is only the output of the debugger, then everything above could be everything that you are looking for - but otherwise you should tell us what you see and what you expected to see.

Look at my article on strings for more information on strings in general, escaping, debugger, etc ..

+4
source

You can do it like this:

 string str = @"abc\xyz"; 
+2
source
 string str = @"abc\xyz"; 
+2
source

You can do it:

 string str = @"abc\xyz"; 

This suggests that the slash is significant, not an escape character.

+1
source

You will need a line prefix with the @ symbol to stop the compiler, trying to treat it as an escape sequence. Therefore string str = @"abc\xyz"; must work.

+1
source

Source: https://habr.com/ru/post/1303928/


All Articles