【问题标题】:c# char.GetNumericValue returns -1c# char.GetNumericValue 返回 -1
【发布时间】: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。当你修复它时,你会得到一个溢出错误。那么为什么不从发布重现问题的实际代码开始呢?
  • 如果您定义了为什么您的预期结果是预期的,这将有所帮助。换句话说,描述你的算法应该是如何工作的,并给出不止一个样本数据。

标签: c# char


【解决方案1】:

您尚未在问题中发布完整的示例,因此我的回答纯粹是猜测。

你可以真的通过使用 LINQ 来简化你的逻辑:

//Assuming you have already checked the 'text' variable
//to make sure its not null or empty
int keyLength = (int)Char.GetNumericValue(text[0]);

if(keyLength < 0)
{
    //keyLength is -1 because the first digit was not a number
    //Handle appropriately
}
char[] keySliced = text.ToCharArray()
                       .Skip(1)
                       .Where(x => char.IsDigit(x))
                       .Take(keyLength)
                       .ToArray();

此 LINQ 所做的是将输入字符串转换为 char 数组 (.ToCharArray())。然后我们跳过第一个字符 (.Skip()),因为我们已经在 keyLength 逻辑中考虑了它。然后我们只关心数字字符(.Where(x =&gt; char.IsDigit(x)))。然后我们取到 keyLength 数量(.Take(keyLength))。并不是说这会将字符按顺序排列,并且最多只能达到字符串的第一个数字中指定的数量(因此"53dad223sfd32" 的输入不会采用53,而是采用@987654329 @)。然后看起来你想要一个 char 数组中的结果,所以我们只需将其具体化为一个数组 (.ToCharArray())

keySliced 现在将是一个 char 数组,其中包含不超过您定义为字符串中第一个字符的长度的所有数字。

对于输入:"5SampleText42964"

结果:

Key[0] -> 4
Key[1] -> 2
Key[2] -> 9
Key[3] -> 6
Key[4] -> 4

我做了一个小提琴here

【讨论】:

  • 哦,非常感谢您的回答!它现在可以正常工作了!
  • 请注意,对于样本数据"5We8The7SlicesIn1HourAnd45Minutes12345",结果将为{ 8, 7, 1, 4, 5 }。并不是说那是错误的,只是不确定您是如何知道预期结果的。
  • @RufusL 是的,我尝试了预期的结果。我用基本术语解释了 LINQ 逻辑,所以如果它符合 OP 想要的内容,他们就会知道。如果没有明确的预期结果,我什至不应该回答一个问题,但我还是试了一下
猜你喜欢
  • 2011-12-28
  • 2018-01-17
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2015-04-20
相关资源
最近更新 更多