Finding floating points in a large string

倾然丶 夕夏残阳落幕 提交于 2019-12-31 03:24:26

问题


I have a large string that has a series of floating points in string. A typical string would have Item X $4.50 Description of item \r\n\r\n Item Z $4.75... There is really no rhyme or reason for the text. I have the lowest already and I need to find all the values in the string. So if it was 10.00 it would find every value that is 10.05 or less. I would assume that some sort of regex would involved to find the values and then I could put them in an array then sort them.

So it would be something like this to find the which of those values fit my criteria.

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

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

My problem is getting those values in the array. I have read this but d+ does not really work with floating points.


回答1:


You should use RegEx:

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

Something like that. Then you can just use:

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

If you need an array:

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

EDIT

I just created a small sample application for you Joe. I compiled it and it worked fine on my machine using the input line from your question. If you are having problems, post your InputString so I can try it out with that. Here is the code I wrote:

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
}


来源:https://stackoverflow.com/questions/6754545/finding-floating-points-in-a-large-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!