2

Please excuse the rubbish title, I don't know how to word it properly. I am wondering how I can use this code:

int cnt = 0;
foreach (char c in test) {
  if (c == '&') cnt++;
}

from this question and instead of adding 1 to the count for 'just' &, add 1 to the count for & or @ or %?

Community
  • 1
  • 1
  • Use it for what? What is the exact problem you are having and what have you done so far to try to solve it? – Sayse Sep 03 '15 at 10:31
  • There is no need to state the problem when I made it clear what I wanted in the question –  Sep 03 '15 at 10:35
  • There is every need to state what you have already tried, SO isn't a free code service, it is here for help with existing problems. – Sayse Sep 03 '15 at 10:36

4 Answers4

7

You can directly count using .Count and with using Linq

 var cnt = test.Count(c => c == '&' || c == '@' || c == '%');
Neel
  • 11,625
  • 3
  • 43
  • 61
4

It's easy, just add more conditions:

int cnt = 0;
foreach (char c in test) {
    if (c == '&' || c == '@' || c == '%') cnt++;
}
Tobbe
  • 1,825
  • 3
  • 21
  • 37
  • Thank you! A helpful answer. I will mark as the answer when I can. I feel so stupid that I didn't use the or operator :( –  Sep 03 '15 at 10:34
3

You could use Regex:

cnt = Regex.Matches(test, "[&@%]").Count
Flynn1179
  • 11,925
  • 6
  • 38
  • 74
1
string pattern = "&@%";
int cnt = 0;
foreach (char c in test)
{
    if (pattern.IndexOf(c) != -1) cnt++;
}
Adrian Stanculescu
  • 1,040
  • 2
  • 13
  • 21