检查字符串是否有斜杠

时间:2016-03-01 19:29:15

标签: c# .net regex string windows

string testStr="thestringhasa\slash";

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

我如何正确地测试以查看字符串是否包含反斜杠,当我尝试使用it语句时,如果在常量中显示新行。

3 个答案:

答案 0 :(得分:6)

你应该使用双斜杠

string testStr=@"thestringhasa\slash";

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

答案 1 :(得分:3)

必须转义反斜杠。请尝试以下方法:

string testStr = @"thestringhasa\slash";

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

答案 2 :(得分:3)

其他两个答案完全正确,但没有人费心解释原因。 \字符在C#字符串中有特殊用途。它是转义字符,所以要有一个包含斜杠的字符串,你必须使用两种方法之一。

  1. 使用字符串文字符号@。前面带有@符号的字符串告诉C#编译器将字符串视为文字,而不是转义任何内容。

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

  3. 因此,以下字符串是等效的:

    var temp1 = @"test\test";
    var test2 = "test\\test";
    
    test1 == test2; // Yields true