【问题标题】:C# String Length returning the wrong amountC# String Length 返回错误的数量
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    在调试中你可以看serialNumber.ToArray()你会注意到字符串开头有char 8237,结尾有8236

    【讨论】:

    • 优秀的收获:)
    猜你喜欢
    • 2018-02-18
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多