我如何检查是否在C字符串存在单个字符? [英] How can I check if a single char exists in a C string?
问题描述
我要检查,如果一个char是在C字符串。该字符是|
用于Linux的管道(其实我也想检查'<
,'>
, '>>
,'和;
)
I want to check if a single char is in a C string. The character is the '|'
used for pipelines in Linux (Actually, I also want to check for '<'
, '>'
, '>>'
, '&'
).
在Java中我可以这样做:
In Java I can do this:
String.indexOf()
但我怎么能做到这一点的C,而不需要通过整个字符串循环(A 的char *
字符串)?
推荐答案
如果您需要寻找您可以使用和strchr
的功能,这样的角色:
If you need to search for a character you can use the strchr
function, like this:
char* pPosition = strchr(pText, '|');
p位置
将 NULL
如果给定的角色还没有被发现。例如:
pPosition
will be NULL
if the given character has not been found. For example:
puts(strchr("field1|field2", '|'));
将输出:|字段2。需要注意的是和strchr
将执行的转发的搜索,搜索的后退的,你可以使用 strrchr
。现在想象(只需提供一个例子),你有一个这样的字符串:变量:值|条件。您可以提取的值的与现场:
Will output: "|field2". Note that strchr
will perform a forward search, to search backward you can use the strrchr
. Now imagine (just to provide an example) that you have a string like this: "variable:value|condition". You can extract the value field with:
char* pValue = strrchr(strchr(pExpression, '|'), ':') + 1;
如果你想要的是首页的字符串内的字符看看到<一个href=\"http://stackoverflow.com/questions/1479386/is-there-a-function-in-c-that-will-return-the-index-of-a-char-in-a-char-array\">this帖子这里SO。您可能需要像 IndexOfAny()
太的这里上的另一个职位,这样使用 strnspn
这一点。
If what you want is the index of the character inside the string take a look to this post here on SO. You may need something like IndexOfAny()
too, here another post on SO that uses strnspn
for this.
相反,如果你正在寻找您可以使用的strstr
功能,像这样的字符串:
Instead if you're looking for a string you can use the strstr
function, like this:
char* pPosition = strstr(pText, "text to find");
这篇关于我如何检查是否在C字符串存在单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!