Karim O.
Karim O.

Reputation: 1365

Split string using backslash

I want to split a string using the backslash ('\'). However, it's not allowed - the compiler says "newline in constant". Is there a way to split using backslash?

//For example...
String[] breakApart = sentence.Split('\'); //this gives an error.

Upvotes: 45

Views: 84650

Answers (3)

Nazar
Nazar

Reputation: 31

you can use @

String[] breakApart = sentence.Split(@"\"); 

Upvotes: 3

Ben Reich
Ben Reich

Reputation: 16324

Try using the escaped character '\\' instead of '\':

String[] breakApart = sentence.Split('\\');

The backslash \ in C# is used as an escape character for special characters like quotes and apostrophes. So when you are trying to wrap the backslash with apostrophes, the backslash together with the final apostrophe is being interpreted as an escaped apostrophe.

Here is a list of character escapes available in C#.

Here is Microsoft's documentation for character literals in C#.

Upvotes: 95

jspcal
jspcal

Reputation: 51914

It's backslash, a character literal.

To do the split:

String[] breakApart = sentence.Split('\\');

Upvotes: 18

Related Questions