【发布时间】:2017-12-08 15:08:43
【问题描述】:
我有一个 13 个字符的字符串。 8C4B99823CB9C。 我将它分配给一个字符串。
string serialNumber = "8C4B99823CB9C";
这个字符串然后进入一个方法
GenerateCode(proxy, serialNumber, product);
在这个方法里面我有这行...
codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
在手表中显示长度为 15。
这是完整的代码
[TestMethod]
public void CanGenerateCodeNumberWithPrefixWithHEX()
{
string serialNumber = "8C4B99823CB9C";
Entity product = new Entity();
product.Attributes["piv_codeseriallength"] = 8;
product.Attributes["piv_codeprefix"] = "G";
string result = GenerateCode(proxy, serialNumber, product);
string expected = "G9823CB9C";
Assert.AreEqual(expected, result, "The Code was not generated correctly");
}
public static string GenerateCode(IOrganizationService _service, string serial_no, Entity product)
{
string codeSerial = null;
//Serial Length
if (product.Attributes.ContainsKey("piv_codeseriallength"))
{
codeSerial = serial_no;
int codeSerialLength = product.GetAttributeValue<int>("piv_codeseriallength");
codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
string prefix = product.Attributes.ContainsKey("piv_codeprefix") ? product.GetAttributeValue<string>("piv_codeprefix") : "";
codeSerial = prefix + codeSerial;
}
return codeSerial;
}
此单元测试失败,因为它认为字符串长度为 15 个字符,因此取错了字符串部分
【问题讨论】:
-
将整个字符串复制/粘贴到文本编辑器中,然后尝试沿字符串左右移动插入符号。您会看到需要在引号周围按左右两次,其中隐藏了一些 unicode 字符
-
查看此处了解类似问题:stackoverflow.com/questions/44475366/…
-
您能否添加您的评论作为答案,以便我打勾
-
我不知道。我不太喜欢发布重复的答案,但我不确定我是否可以将这个作为重复的答案关闭,因为表达问题的方式完全不同
标签: c# string string-length