2013-01-02 36 views
0

我想看看是否有不同/更好的方式来解析我有一个字符串。从字符串解析一个int的更好的方法

字符串是“#def xyz [timer = 50,fill = 10]”。 从这个字符串我试图检索计时器和填充值。

我目前拥有的代码是:

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); 

有什么建议?

在此先感谢!

+2

您是否试过正则表达式? – k0stya

+6

你的意思是*更好*是什么意思?更容易阅读?更高性能? –

+0

正则表达式应该可以帮助你 – platon

回答

6

我可能会使用正则表达式。例如:

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); 
     } 
    } 
} 

注:

  • 具有非负整数这仅涉及
  • 它将失败(具有异常)如果值超出了范围为int

我会说,它表明你正在做的事情比那些Remove呼叫更清楚...

+0

非常感谢! – Miguel

1
 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"); 
0

我喜欢在可以的情况下使用拆分,在大多数情况下,它比正则表达式快得多 - 我没有测试,但我预计在这里速度会更快。当然这个代码中的错误检查很少。

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()); 

}