gpt4 book ai didi

C# 字符串长度返回错误的数量

转载 作者:太空宇宙 更新时间:2023-11-03 19:46:30 27 4
gpt4 key购买 nike

我有一个 13 个字符的字符串。 8C4B99823CB9C。我将它分配给一个字符串。

 string serialNumber = "‭8C4B99823CB9C‬";

这个字符串然后进入一个方法

GenerateCode(proxy, serialNumber, product);

在这个方法中我有这一行...

codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);

在 watch 中,长度显示为 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 字符。找出答案的一个好方法是将完整的字符串复制并粘贴到文本编辑器中,然后尝试沿着字符串左右移动插入符号。您会看到您需要在引号周围向左或向右按​​两次,这意味着有更多的字符会出现在眼前。当然,另一种方法是在十六进制编辑器中简单地打开字符串。

假设您只需要简单的字符,您可以使用正则表达式清理您的输入,去除多余的字符:

var sanitizedInput = Regex.Replace(input, @"[^\w:/ ]", string.Empty);

关于C# 字符串长度返回错误的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44917905/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com