Reputation:
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
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.
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.
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
Reputation: 34152
You should use double slashes
string testStr=@"thestringhasa\slash";
if(testStr.Contains("\\"))
{
//Code to process string with \
}
Upvotes: 6
Reputation: 3959
The backslash must be escaped. Try the following:
string testStr = @"thestringhasa\slash";
if (testStr.Contains("\\"))
{
//Code to process string with \
}
Upvotes: 5