0

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);
}
3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by gloris
2

\ 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);

Edited by apegram: n/a

1

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...;)

Edited by ddanbe: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.