[英]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. 我如何正确地测试以查看字符串是否包含反斜杠,当我尝试使用it语句时,如果在常量中显示新行。
You should use double slashes 你应该使用双斜杠
string testStr=@"thestringhasa\slash";
if(testStr.Contains("\\"))
{
//Code to process string with \
}
The backslash must be escaped. 必须转义反斜杠。 Try the following:
请尝试以下方法:
string testStr = @"thestringhasa\slash";
if (testStr.Contains("\\"))
{
//Code to process string with \
}
The other two answers are entirely correct, but no one bothered to explain why. 其他两个答案完全正确,但没有人费心解释原因。 The \\ character has a special purpose in C# strings.
\\字符在C#字符串中有特殊用途。 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.
前面带有@符号的字符串告诉C#编译器将字符串视为文字,而不是转义任何内容。
Use the escape character to tell the C# compiler there is a special character that is actually part of the string. 使用转义字符告诉C#编译器有一个特殊字符,它实际上是字符串的一部分。
So, the following strings are equivalent: 因此,以下字符串是等效的:
var temp1 = @"test\test";
var test2 = "test\\test";
test1 == test2; // Yields true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.