从字符串文件中获取特定元素

时间:2012-04-24 16:33:21

标签: c#

大家好我正在将一个文件读入字符串变量,但是我想知道将字符串中的特定元素返回到新变量的最佳方法是什么。

我有以下字符串数据文件:

[TEST1]
mem.consumed.average = 965608688
cpu.usagemhz.average = 18653
Hosts = 3
Points = 1535
RAM = 1535.96
CPU = 191.79
Powered_on VMs = 70
Powered_on RAM = 1049.02
Powered_on CPU = 410.15
Powered_on Points = 1051
Provisioned VMs = 74
Provisioned RAM = 1057.02
Provisioned CPU = 416.59
Provisioned Points = 1059

[TEST2]
mem.consumed.average = 298762549
cpu.usagemhz.average = 7782
Hosts = 4
Points = 1535
RAM = 1535.96
CPU = 191.79
Powered_on VMs = 54
Powered_on RAM = 303.00
Powered_on CPU = 266.29
Powered_on Points = 303
Provisioned VMs = 60
Provisioned RAM = 330.00
Provisioned CPU = 295.28
Provisioned Points = 330

我只想返回“主机”的值,所以在上面的情况下只有Hosts = 3(来自[TEST1])和Hosts = 4(来自[TEST2])。任何想法都将非常感激:)

3 个答案:

答案 0 :(得分:1)

我会逐行阅读并寻找line.StartsWith("Hosts") - 如果这是真的,请提取您需要的内容。

答案 1 :(得分:1)

答案 2 :(得分:0)

如果您只想将其作为字符串搜索,为什么不使用.indexOf函数。

所以它会是

int a = data.indexOf('hosts');
int b = data.indexOf('points');

然后

string hosts data = data.Substring(a,b);

你必须改变索引以获得确切的值,但它应该很容易 像

这样的东西
string hosts data = data.Substring(a + 7,b - 2);