0

How to count the number of backslashes in a string?
I've tried the following, but none of them worked.

string s = @"\a\a\n\u\u0013((((\a\b\n"; // output must be 8
int count = s.Count(a => a == "\\"); // Operator == cant be applied of type char & string
int count = s.Count(a => a == "\"); // newline in constant
int count = s.Split('\\').Length // it doesnt count
Rob
  • 26,989
  • 16
  • 82
  • 98
Vincent
  • 29
  • 1
  • 6
  • 1
    For each of your problems a simple google search would yield tons of posts, like the ones I choose to close your question with. Please be more careful next time *before* asking a question. – Patrick Hofman Jul 10 '17 at 07:29

1 Answers1

4

Your first attempt was nearly correct; but you need to compare a character and a character, not a character and a string.

Your code should be:

int count = s.Count(a => a == '\\');
Rob
  • 26,989
  • 16
  • 82
  • 98
  • i tried your suggestion and there's no error in it but the result is still zero – Vincent Jul 10 '17 at 07:26
  • @Vincent Then you must be testing against another string. I've run the code verbatim, and it prints 8. – Rob Jul 10 '17 at 07:27