[英]How to compare strings with multiple line
I have a method which is generating the following, which i am saving in a string, lets say that string is name output
我有一种生成以下内容的方法,我将其保存在字符串中,可以说字符串是名称
output
HDRPB509030978SENTRIC MUSIC 01.102013070914290620130709
GRHREV0000102.100000000000
REV0000000000000000AWAITING YOUR CALL EN00000000044021 POP000436Y ORI PHIL
TRL000010000000100000022
what i am trying is to hard code the above line and compare it to the generated output. 我正在尝试的是对上面的行进行硬编码,并将其与生成的输出进行比较。 I am hard-coding like this i am replacing the next lines with \\n like this
我像这样硬编码,我用\\ n替换下一行
string hardCoded = " HDRPB509030978SENTRIC MUSIC \n01.102013070914290620130709 \n GRHREV0000102.100000000000 \n REV0000000000000000AWAITING YOUR CALL \nEN00000000044021 POP000436Y ORI PHIL \n TRL000010000000100000022 "
now when i compare 现在,当我比较
output == hardCoded
OR 要么
Assert.AreEqual(output,hardCoded);
is is false. 是错误的。 how to compare these two
如何比较这两个
Comparing multi-line strings is not different from comparing single-line strings: the strings you compare must match character-for-character, including whitespace and line breaks. 比较多行字符串与比较单行字符串没有什么不同:比较的字符串必须匹配字符对字符,包括空格和换行符。 If your generated string uses
\\r\\n
separator instead of \\n
, then the string constant that you expect to get must contain the same separator as well. 如果生成的字符串使用
\\r\\n
分隔符而不是\\n
,则您期望获得的字符串常量也必须包含相同的分隔符。 You can check the kind of separators that you use by setting a breakpoint, and examining the string that you generate in a debugger. 您可以通过设置断点并检查在调试器中生成的字符串来检查使用的分隔符类型。
Rather than hard-coding the string for unit testing, consider reading it from a resource. 与其硬编码字符串以进行单元测试,不如考虑从资源中读取它。 This would let you edit the string in a text editor, and inspect it visually for differences.
这样一来,您就可以在文本编辑器中编辑字符串,并直观地检查是否存在差异。
Finally, if you do not need the whitespace to match, you could define a function that compares strings excluding whitespace: 最后,如果不需要空格来匹配,则可以定义一个函数来比较排除空格的字符串:
static bool EqualsExcludingWhitespace(String a, String b) {
return a.Where(c => !Char.IsWhiteSpace(c))
.SequenceEqual(b.Where(c => !Char.IsWhiteSpace(c)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.