且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串是否包含某个字符?

更新时间:2022-11-17 14:58:02

通过使用 strchr(),例如:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char str[] = "Hi, I'm odd!";
  int exclamationCheck = 0;
  if(strchr(str, '!') != NULL)
  {
    exclamationCheck = 1;
  }
  printf("exclamationCheck = %d\n", exclamationCheck);
  return 0;
}

输出:

exclamationCheck = 1

exclamationCheck = 1

如果您正在寻找一种简洁的班轮,那么您可以按照@melpomene的方法进行操作:

If you are looking for a laconic one liner, then you could follow @melpomene's approach:

int exclamationCheck = strchr(str, '!') != NULL;


如果不允许使用C字符串库中的方法,则按照@SomeProgrammerDude的建议,您可以简单地对字符串进行迭代,并且如果有任何字符是感叹号,如本示例所示:


If you are not allowed to use methods from the C String Library, then, as @SomeProgrammerDude suggested, you could simply iterate over the string, and if any character is the exclamation mark, as demonstrated in this example:

#include <stdio.h>

int main(void)
{
  char str[] = "Hi, I'm odd";
  int exclamationCheck = 0;
  for(int i = 0; str[i] != '\0'; ++i)
  {
    if(str[i] == '!')
    {
      exclamationCheck = 1;
      break;
    }
  }
  printf("exclamationCheck = %d\n", exclamationCheck);
  return 0;
}

输出:

exclamationCheck = 0

exclamationCheck = 0

请注意,当找到至少一个感叹号时,您可以中断循环,这样就无需遍历整个字符串.

Notice that you could break the loop when at least one exclamation mark is found, so that you don't need to iterate over the whole string.

PS: main()在C和C ++中应该返回什么? int ,而不是 void .