2016-08-16 88 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()其使用預測表達式來匹配的元素相匹配。