如何检查 C 字符串中是否存在单个字符? [英] How can I check if a single char exists in a C string?

查看:12
本文介绍了如何检查 C 字符串中是否存在单个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查单个字符是否在 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 中做到这一点,而不循环整个字符串(char* 字符串)?

But how can I do this in C, without looping through the whole string (a char* string)?

推荐答案

如果需要搜索字符可以使用strchr函数,如下:

If you need to search for a character you can use the strchr function, like this:

char* pPosition = strchr(pText, '|');

如果未找到给定字符,则

pPosition 将为 NULL.例如:

pPosition will be NULL if the given character has not been found. For example:

puts(strchr("field1|field2", '|'));

将输出:|field2".请注意,strchr 将执行 forward 搜索,要搜索 backward 您可以使用 strrchr.现在想象一下(只是提供一个例子)你有一个这样的字符串:变量:值|条件".您可以使用以下方法提取 value 字段:

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;

如果您想要的是字符串中字符的 index,请查看 这篇文章在这里.您可能还需要 IndexOfAny() 之类的东西,这里关于 SO 的另一篇文章使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆