Finding floating points in a large string

前端 未结 1 1285
失恋的感觉
失恋的感觉 2021-01-23 03:33

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... Ther

相关标签:
1条回答
  • 2021-01-23 04:16

    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 讨论(0)
提交回复
热议问题