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

Ale*_*lex 6 c arrays string char string-comparison

我对 C 编程还很陌生,例如,如果我们有:

void main(int argc, char* argv[]){

  char checkThisLineForExclamation[20] = "Hi, I'm odd!"
  int exclamationCheck;
}
Run Code Online (Sandbox Code Playgroud)

所以有了这个,exclamationCheck如果“!”我将如何设置为 1 存在,如果不存在则为 0?非常感谢您提供的任何帮助。

gsa*_*ras 6

通过使用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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

感叹号检查 = 1

如果您正在寻找简洁的单衬里,那么您可以遵循@melpomene 的方法:

int exclamationCheck = strchr(str, '!') != NULL;
Run Code Online (Sandbox Code Playgroud)

如果不允许使用 C 字符串库中的方法,那么,正如@SomeProgrammerDude 建议的那样,您可以简单地遍历字符串,如果有任何字符是感叹号,如本例所示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

感叹号检查 = 0

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


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

  • 或者稍微简单一点:`int exclamationCheck = strchr(str, '!') != NULL;` (2认同)