如何将字符串的特定字符解析为整数?

时间:2012-06-26 07:03:15

标签: c# winforms string parsing integer

string abc = "07:00 - 19:00"
x  = int.Parse(only first two characters) // should be 7
y  = int.Parse(only 9th and 10th characters) // should be 19

我怎么能这样说呢?

2 个答案:

答案 0 :(得分:7)

使用字符串类的Substring方法提取所需的字符集。

string abc = "07:00 - 19:00";
x  = int.Parse(abc.Substring(0,2)); // should be 7
y  = int.Parse(abc.Substring(8,2)); // should be 19

答案 1 :(得分:3)

没有int.Parse占用范围,所以:

  • 编写自己的解析器(是的)
  • 首先使用Substring,然后在子字符串
  • 上使用int.Parse

这样:

x = int.Parse(abc.Substring(0,2));