user5910494
user5910494

Reputation:

Check a String for a Slash

string testStr="thestringhasa\slash";

if(testStr.Contains("\"))
{
    //Code to process string with \
}

How do I properly test to see if a string contains a backslash, when I try the it statement if says a New Line in constant.

Upvotes: 5

Views: 19438

Answers (3)

Kevin
Kevin

Reputation: 1472

The other two answers are entirely correct, but no one bothered to explain why. The \ character has a special purpose in C# strings. It is the escape character, so to have a string that contains a slash, you have to use one of two methods.

  1. Use the string literal symbol @. A string preceded by the @ symbol tells the C# compiler to treat the string as a literal and not escape anything.

  2. Use the escape character to tell the C# compiler there is a special character that is actually part of the string.

So, the following strings are equivalent:

var temp1 = @"test\test";
var test2 = "test\\test";

test1 == test2; // Yields true

Upvotes: 8

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

You should use double slashes

string testStr=@"thestringhasa\slash";

if(testStr.Contains("\\"))
{
    //Code to process string with \
}

Upvotes: 6

Marc
Marc

Reputation: 3959

The backslash must be escaped. Try the following:

string testStr = @"thestringhasa\slash";

if (testStr.Contains("\\"))
{
    //Code to process string with \
}

Upvotes: 5

Related Questions