Search code examples
c#stringstring-parsing

A better way of parsing an int from a string


I'm trying to see if there is a different/better way of parsing a string that I have.

The string is "#def xyz[timer=50, fill=10]". From this string I am trying to retrieve the timer and fill values.

The code I currently have is:

string def = "#def xyz[timer=50, fill=10]";
string _timer = def.Remove(def.IndexOf(","));
_timer = _timer.Remove(0, _timer.IndexOf("=", _timer.IndexOf("timer")) + 1);

string _fill = def.Remove(def.IndexOf("]"));
_fill = _fill.Remove(0, _fill.IndexOf("=", _fill.IndexOf("fill")) + 1);

int timer = Int32.Parse(_timer);
int fill = Int32.Parse(_fill);

Any suggestions?

Thanks in advance!


Solution

  • I would probably use a regular expression. For example:

    using System;
    using System.Text.RegularExpressions;
    
    class Test
    {
        static void Main()
        {
            // You can create the regex once and reuse it, of course. Adjust
            // as necessary if the name isn't always "xyz" for example.
            Regex regex = new Regex(@"^#def xyz\[timer=(\d+), fill=(\d+)\]$");
            string input = "#def xyz[timer=50, fill=10]";
            Match match = regex.Match(input);
            if (match.Success)
            {
                int fill = int.Parse(match.Groups[1].Value);
                int timer = int.Parse(match.Groups[2].Value);
                Console.WriteLine("Fill={0}, timer={1}", fill, timer);
            }
        }
    }
    

    Notes:

    • This only deals with non-negative integers
    • It will fail (with an exception) if the value is out of range for an int

    I'd say it indicates what you're doing more clearly than those Remove calls though...