Miguel
Miguel

Reputation: 1177

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!

Upvotes: 0

Views: 198

Answers (3)

Hogan
Hogan

Reputation: 70513

I like using split when I can, it is much faster than regex in most cases -- I didn't test but I expect it would be faster here. Of course there is very little error checking in this code.

void Main()
{
  string def = "#def xyz[timer=50, fill=10]";

  string [] inBracket = def.Split("[]".ToCharArray());

  string [] elements = inBracket[1].Split(",".ToCharArray());

  int timer = int.Parse(elements[0].Split("=".ToCharArray())[1]);

  int fill = int.Parse(elements[1].Split("=".ToCharArray())[1]);

  Console.WriteLine("timer = "+timer.ToString());
  Console.WriteLine("fill = "+fill.ToString());

}

Upvotes: 0

VladL
VladL

Reputation: 13033

      Match m = Regex.Match("#def xyz[timer=50, fill=10]", "timer=([0-9]+?), fill=([0-9]+?)[]]");

      string timer = m.Result("$1");
      string fill = m.Result("$2");

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

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

Upvotes: 6

Related Questions