Reputation: 945
I have a string of 13 characters. 8C4B99823CB9C. I am assigning it to a string.
string serialNumber = "8C4B99823CB9C";
This string then enters a method
GenerateCode(proxy, serialNumber, product);
Inside this method I have this line...
codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
In the watch this is showing the length as 15.
Here is the full code
[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;
}
This unit test fails because it thinks the string is 15 characters long and so taking the wrong section of the string
Upvotes: 1
Views: 2628
Reputation: 39047
You have hidden unicode characters in your string. One good way to find out is to copy&paste the full string into a text editor, then try to move the caret left and right along the string. You'll see that you need to press left or right twice around the quotes, meaning that there's more characters then meet the eye. Of course, another way would be simply to open the string in a hexadecimal editor.
Assuming you only need simple characters, you can sanitize your input with a regex, to strip the extra characters:
var sanitizedInput = Regex.Replace(input, @"[^\w:/ ]", string.Empty);
Upvotes: 3
Reputation: 3161
In debug you can watch serialNumber.ToArray()
you will notice that there is char 8237 at the begining of string and 8236 at the end
Upvotes: 3