Hi,
how work with \ ?
Now i get error where is \, how fix this code?
This option is not me: instead of \ use \\

string word = "Name\UserName";
string[] words = word.Split('\');

foreach (string name in words)
{
      Console.WriteLine(name);
}

Recommended Answers

All 3 Replies

\ is used to escape special characters in strings or chars. To use it normally, you either need to escape it (making it \\) or you can use the @ character in front of the entire string.

string oneWay = "C:\\Temp\\somefile.txt";
string anotherWay = @"C:\Temp\somefile.txt";

So for your code, you can do this:

string word = @"Name\UserName";
string[] words = word.Split('\\');

foreach (string s in words)
    Console.WriteLine(s);

Or this:

string word = "Name\\UserName";
string[] words = word.Split('\\');

foreach (string s in words)
    Console.WriteLine(s);

If you want to use \ in a string you need to precede it with another \ like "Name\\UserName"; or precede the whole string with the @ char, like @"Name\UserName";.
\ is interpreted as an escape sequence to be able to use a newline character '\n' or other in your strings instead of the letter 'n'. Look here for more info.
EDIT: apegram beated me at this by some lengths...;)

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.