如何在c#中使用.IndexOf和.Substring从文本中获取值?
我需要对字符串变量中的几个值求和 这是我的变量:如何在c#中使用.IndexOf和.Substring从文本中获取值?,c#,.net,string,indexing,C#,.net,String,Indexing,我需要对字符串变量中的几个值求和 这是我的变量: string strBillHeader = "Invoice Details INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE 01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014 01/11/2014,New Corpbundle 7,-7,01/11/2014,30/11/2014 01/11/2014,New Corpbun
string strBillHeader = "Invoice Details
INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,-7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,Missed Call ALERT with Offer,2,01/11/2014,30/11/2014"
在这种情况下,我需要得到(7,-7,7,2)的值?结果得到9分
我试着这样做:
for (int x = 4; x <= countCommas - 3; x += 4)
{
int firstCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + x);
int secondCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + (x + 1));
string y = strBillHeader.Substring(firstCommaIndex + 1, 1);
chargeAmount = Convert.ToInt32(y);
//chargeAmount = Int32.Parse(strBillHeader.Substring(firstCommaIndex, secondCommaIndex - firstCommaIndex));
TotalChargeAmount += ChargeAmount;
//string AstrBillHeader = strBillHeader.Split(',')[0];
}
for(int x=4;x如果这些逗号和换行符总是在那里,这应该可以:
var lines = strBillHeader.Split(Environment.NewLine).Skip(2);
int total = lines.Split(',').Sum(line => Convert.ToInt32(line[2]));
因此,您将发票拆分为几行,并丢弃前两行(“代码>发票详细信息”和“<代码>发票日期,发票描述,值,从日期到日期”
”)。然后在逗号上拆分每行,并取第三个值-第一个值是日期,第二个值是“<代码>新刚玉7”第三部分是您的值。您将该值解析为一个int
,然后对整个批次进行求和
您可能会发现,您需要正确地过滤掉这些行,而不仅仅是假设您可以跳过前两行并使用其余的行,但这应该可以让您开始了。使用string.Split和Linq表达式对行的第二列求和。您为什么不想要最后一行中的2呢?我想要它,但我忘了在问题中添加它……对不起你在那个字符串中有换行符,或者它只是一行文本?有趣的,请检查你的数学。没有对单个或多行问题的澄清,我认为这个答案是正确的。