【问题标题】:Finding floating points in a large string在大字符串中查找浮点数
【发布时间】:2011-07-19 21:46:27
【问题描述】:

我有一个大字符串,字符串中有一系列浮点数。一个典型的字符串是Item X $4.50 Description of item \r\n\r\n Item Z $4.75... 文本确实没有押韵或理由。我已经是最低的了,我需要找到字符串中的所有值。因此,如果它是10.00,它将找到每个小于等于10.05 的值。我会假设某种正则表达式会涉及到查找值,然后我可以将它们放入一个数组中然后对它们进行排序。

因此,找出这些值中的哪一个符合我的标准是这样的。

int [] array;
int arraysize;
int lowvalue;
int total;

for(int i = 0; i<arraysize; ++i)
{
    if(array[i] == lowvalue*1.05) ++total;
}

我的问题是在数组中获取这些值。我已阅读 this,但 d+ 并不能真正用于浮点。

【问题讨论】:

  • 明确一点,你需要10.00下面的所有值,还是专门找最小值?
  • @StriplingWarrior 这是一个错字,它的所有值都必须是最低值的 105% 或更少。
  • 只是这些值,或者你需要这些值的描述吗?

标签: c# regex string floating-point double


【解决方案1】:

你应该使用正则表达式:

Regex r = new RegEx("[0-9]+\.[0-9]+");
Match m = r.Match(myString);

类似的东西。然后你可以使用:

float f = float.Parse(m.value);

如果你需要一个数组:

MatchCollection mc = r.Matches(myString);
string[] myArray = new string[mc.Count];
mc.CopyTo(myArray, 0);

编辑

我刚刚为您创建了一个小型示例应用程序,Joe。我编译了它,它使用您问题中的输入行在我的机器上运行良好。如果您遇到问题,请发布您的 InputString,以便我可以尝试一下。这是我写的代码:

static void Main(string[] args)
{
    const string InputString = "Item X $4.50 Description of item \r\n\r\n Item Z $4.75";

    var r = new Regex(@"[0-9]+\.[0-9]+");
    var mc = r.Matches(InputString);
    var matches = new Match[mc.Count];
    mc.CopyTo(matches, 0);

    var myFloats = new float[matches.Length];
    var ndx = 0;
    foreach (Match m in matches)
    {
        myFloats[ndx] = float.Parse(m.Value);
        ndx++;
    }

    foreach (float f in myFloats)
        Console.WriteLine(f.ToString());

    // myFloats should now have all your floating point values
}

【讨论】:

  • 您不能将匹配项复制到字符串集合中。
  • @svick - This says you can。它应该将 MatchCollection 项复制到一个数组中,然后您可以遍历数组并利用 Value 属性来获取字符串。
  • 这表示您可以复制到数组。它并不是说您可以复制到字符串数组。而且您的代码实际上不起作用,CopyTo() throws InvalidCastException.
  • @icemanind 这给出的结果真的很奇怪。它正在拉动甚至是字符串一部分的东西。
  • @Joe - 嗯,这很奇怪。我很快把我的答案放在一起。给我几分钟,我将使用我使用您问题中的输入字符串测试的答案重新编辑我的答案。
猜你喜欢
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多