【发布时间】:2018-04-04 19:01:15
【问题描述】:
我有以下代码可以在文本中找到隐藏的键。
private static string FindKey(string text)
{
int keyLength = text[0];
int[] keySliced = new int[keyLength];
char[] fullText = text.ToCharArray();
char[] chars = new char[text.Length - (1 + keyLength)];
Console.WriteLine("Key Length -> {0}", keyLength);
int y = 0;
for(int i = 1 + chars.Length; i < 1 + chars.Length + keyLength; i++)
{
char chr = fullText[i];
keySliced[y] = Convert.ToInt32(char.GetNumericValue(chr));
Console.WriteLine("Key[{0}] -> {1}", y, keySliced[y]);
y++;
}
}
问题是当我运行这段代码时,它会返回类似这样的内容
Input: 5SampleText42964
Result:
Key[0] -> 4
Key[1] -> 2
Key[2] -> 9
Key[3] -> 6
Key[4] -> -1 //Here is the problem
Expected Result:
Key[0] -> 4
Key[1] -> 2
Key[2] -> 9
Key[3] -> 6
Key[4] -> 4
Key[4] 值始终为 -1,但它不应该
有什么解决办法吗?
【问题讨论】:
-
每the docs。该方法返回
"The numeric value of c if that character represents a number; otherwise, -1.0."。在不知道您的输入的情况下,这将很难回答。您的问题必须包含minimal reproducible example -
int keyLength = text[0];正在返回字符串中索引0处字符的 ASCII 值。int keyLength = Convert.ToInt32(text[0]);会给你转换为整数的字符的数值(或者如果转换失败会抛出异常) -
你的代码甚至不会编译,更不用说给你声称它给出的结果了。
-
另外,您的代码无法编译。您必须实际返回
string。当你修复它时,你会得到一个溢出错误。那么为什么不从发布重现问题的实际代码开始呢? -
如果您定义了为什么您的预期结果是预期的,这将也有所帮助。换句话说,描述你的算法应该是如何工作的,并给出不止一个样本数据。