简体   繁体   English

在C中如何在字符串中找到'\\'字符?

[英]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. 假设我有一个用户输入的字符串asdfgh\\hj ,我希望在String中找到\\字符的索引。 How I can do it in C? 我怎么能用C做呢?

I tried strchr() function as strchr("asdfgh\\hj",'\\') but compiler throws an error. 我尝试strchr()函数作为strchr("asdfgh\\hj",'\\')但编译器抛出错误。

Then I used == operator but same problem with it — again the compiler throws an error. 然后我使用==运算符,但同样的问题 - 再次编译器抛出错误。

I tried strchr() function as strchr("asdfgh\\hj",'\\') but compiler throws an error 我尝试strchr()函数作为strchr("asdfgh\\hj",'\\')但编译器抛出错误

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 . 它用于定义“特殊”不可打印字符,例如换行符\\n That is why the backslash itself \\ needs escaping, like this: 这就是反斜杠本身\\需要转义的原因,如下所示:

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

尝试这个:

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

C standard says, C11 6.4.4.4: C标准说,C11 6.4.4.4:

The double-quote " and question-mark ? are representable either by themselves or by the escape sequences \\" and \\? 双引号"和问号?可以通过它们自己或转义序列来表示\\"\\? , respectively, but the single-quote ' and the backslash \\ shall be represented, respectively, by the escape sequences \\' and \\\\ . 分别,但单引号'和反斜杠\\应表示,分别由转义序列\\'\\\\

So use 所以使用

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

instead. 代替。

In C the backslash is used for hard typed characters like \\n . 在C中,反斜杠用于\\n等硬类型字符。 So you need to write \\\\ for the \\ itself: 所以你需要为\\本身写\\\\

char *backslash = strch("some text containing \\ ...", '\\');

Note that in the string you provided the \\ also need to be writen \\\\ otherwise it will be considered as \\h which has no meaning. 请注意,在您提供的字符串中\\也需要写入\\\\否则它将被视为\\h ,这没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM