char.isnumber('。')在" en-US"上返回false区域设置

时间:2017-06-29 17:09:29

标签: c# .net winforms

我正在制作适用于g代码的Windows窗体应用程序。 基本上输入的字符串可能如下所示:

  

X32.2Y47Z100.5

为了首先检索每个数字,我必须找出代表数字的单个子字符串有多长。

在我的加载事件中我有这些:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

在这些行之后,语言环境本身具有价值" en-US" 但以下两个都返回false。

char.IsNumber('.');
char.IsNumber(',');

当string包含'时,convert.toDouble()也会失败。'或','。

2 个答案:

答案 0 :(得分:3)

问题在于,您希望字符.,被视为数字,而不是。当与实际数字一起使用时,它们仅被视为有效数字的一部分,并且只有当它们的位置根据当前文化正确时才被视为有效数字。

您可以使用RegExstring.Split方法在x,y和z字符上拆分字符串,然后您可以使用double.TryParse转换拆分分为双打:

private static void Main()
{
    string input = "X32.2Y47Z100.5";

    string[] inputParts = input.Split(new[] {'X', 'Y', 'Z'}, 
        StringSplitOptions.RemoveEmptyEntries);

    if (inputParts.Length == 3)
    {
        double x, y, z;
        double.TryParse(inputParts[0], out x);
        double.TryParse(inputParts[1], out y);
        double.TryParse(inputParts[2], out z);
        Console.WriteLine($"The values are: x = {x}, y = {y}, z = {z}");
    }
    else
    {
        Console.WriteLine("Input was not in a valid format.");
    }

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

<强>输出

enter image description here

答案 1 :(得分:0)

  1. 使用正则表达式将所有字母替换为&#34;;&#34;

    Regex.Replace(YourInputString, "[^0-9.,]", ";")
    
  2. 使用&#34;;&#34;

    拆分结果
    var YourInputStringArray = YourInputString.Split(';')
    
  3. 删除所有空条目

    YourInputStringArray =  YourInputStringArray .Where(x => !string.IsNullOrEmpty(x)).ToArray();
    
  4. 将其转换为双倍

    foreach(var inputString in YourInputStringArray)
    {
       if(double.TryParse(inputString, out var result)){
           // Here is your double value
       }
    }
    
相关问题