开发者

Finding floating points in a large string

开发者 https://www.devze.com 2023-03-21 18:24 出处:网络
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 t

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 hav开发者_运维问答e 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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消