Search code examples
cstringstrchr

In C how do I find the '\' character in a string?


Suppose I have a string entered by the user asdfgh\hj, and I wish to find out the index of \ character in a String. How I can do it in C?

I tried strchr() function as strchr("asdfgh\hj",'\') but compiler throws an error.

Then I used == operator but same problem with it — again the compiler throws an error.


Solution

  • I tried strchr() function as strchr("asdfgh\hj",'\') but compiler throws an error

    That's the right function! The reason you get an error is because \ is a special "escape" character. It is used to define "special" non-printable characters, such as newline \n. That is why the backslash itself \ needs escaping, like this:

    strchr("asdfgh\\hj",'\\')