检查一个字符串是否包含斜杠

5
string testStr="thestringhasa\slash";

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

当我尝试使用if语句检测一个字符串是否包含反斜杠时,应该如何正确测试?但是当我尝试使用if语句时,它会显示常量中有一个新行。

3个回答

7
其他两个答案都是正确的,但没有人费心去解释为什么。在C#字符串中,\字符有着特殊的用途。它是转义字符,所以如果要包含一个斜杠的字符串,你必须使用以下两种方法之一:
  1. 使用字符串字面量符号@。在@符号前的字符串告诉C#编译器将字符串视为文字而不转义任何内容。

  2. 使用转义字符来告诉C#编译器有一个特殊字符实际上是字符串的一部分。

因此,以下字符串是等效的:
var temp1 = @"test\test";
var test2 = "test\\test";

test1 == test2; // Yields true

6

你应该使用双斜杠

string testStr=@"thestringhasa\slash";

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

2
同时,testStr 应该包含转义斜杠 \\\ 以进行适当的测试。或者使用字符串 testStr=@"thestringhasa\slash"; - va.

4
反斜杠必须被转义。请尝试以下操作:

\\

string testStr = @"thestringhasa\slash";

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接