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

C# String Length returning the wrong amount

我有一个 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 个字符长,所以取错了字符串部分

在调试中你可以观察serialNumber.ToArray()你会注意到字符串的开头是8237,结尾是8236

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

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

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