Denisas
Denisas

Reputation: 13

c# How to split a string using a back slash (double slash not working)

I'm trying to split a string using the '\'.

I've read the topic How to split using a back slash, where are a good advice to use the escaped character '\\' instead of '\' in Split method.

However if I'm using '\\', this "eating" the first symbols of my words I want to split.

Here my code:

        string firstString = "one\two\three";
        char a = '\\';
        string[] splittedString = firstString.Split(a);
        foreach (string s in splittedString)
        {
            Console.WriteLine(s);
        }

//Output is "one wo hree"

So WHY? Where is my mistake?

Upvotes: 0

Views: 4780

Answers (2)

Gareth
Gareth

Reputation: 911

You either need to escape the \ in firstString like this

string firstString = "one\\two\\three";

Or prefix it with an "@" like this

string firstString = @"one\two\three";

These might help https://blogs.msdn.microsoft.com/csharpfaq/2004/03/12/what-character-escape-sequences-are-available/ and http://www.yoda.arachsys.com/csharp/strings.html

Upvotes: 3

Alexey Subbota
Alexey Subbota

Reputation: 972

Try to rewrite

string firstString = "one\\two\\three";

Upvotes: 1

Related Questions