2016-08-16 60 views
1
Format = PPYYMMNNNN 

我只需要知道如何只计算字母N. 我发现的例子是计算所有的字母。 我已经尝试了一些代码,但不工作,我不知道错误在哪里。如何计算文本框中的值?

 format = docctrlTable.format; 
     int count = 0; 
     for (int i = 0; i < format.Length; i++) 
     { 
      String a = format[i] + ""; 

      if (a.Equals("N")) 
      { 
       count = count + 1; 
      } 
     } 
     return count; 
+0

什么是错误您收到? – Kinetic

+0

如果我只将格式更改为PPYYMMNN 2 N,它仍然会得到4 n – David

+0

嗯,它适用于我! – Kinetic

回答

0

你可以试试这个:

string Format = "PPYYMMNNNN"; 
    int count=0; 
    foreach(char c in Format) 
    { 
     if(c=='N') 
      count++; 
    } 

    Console.WriteLine(count); 
1

这可以在单个表达式中完成。

int countOfN = format.Count(c => 'N' == c); 

这适用使用LINQ功能Count()其使用预测表达式来匹配的元素相匹配。