在数组中仅比较一个字符

Comparing only one char in an array

本文关键字:一个 字符 数组 比较      更新时间:2023-10-16

我是新生。

这是我的代码

#include <iostream>
#include <string.h>
using namespace std;
int main() {
char time[20];
       scanf("%s",time);
       // command and "hello" can be less than, equal or greater than!
       // thus, strcmp return 3 possible values
       if (strcmp(time, "PM") == 0)
       {
          printf("It's PM n");
       }

    return 0;
}

假设我有一个输入 12:13:14 pm

我想找出是AM还是PM。但是上面的代码只能发现整个炭阵列是否为" pm"。我看过其他帖子,我无法理解它们。

strcmp检查整个字符串以保持平等,检查子字符串使用strstr

if (strstr(time, "PM") != NULL)
  printf("It's PM n");

附带说明,仅保留20个char的输入可能会很麻烦。


另外,您的代码看起来像C ,而不是C,如果是这种情况,请使用cinstd::string

std::string time;
std::cin >> time;
if(time.find("PM") != std::string::npos)
  std::cout << "It's PM n";

您可以使用函数'char *strstr(const char *str1,const char *str2(;' - 这是指在Str2中指定的整个字符序列中首次出现的指针,或者如果序列不存在Str1中的序列。

if (strstr(time,"PM")!= NULL)
     printf("It's PM n");

您可以使用strcmp和strstr两者都可以确保仅在末尾发生PM。

 if (strcmp(strstr(time,"PM"),"PM")== 0)
     printf("It's PM n");

此外,您的代码也会给出编译错误,因为您尚未包含stdio.h并使用scanf和printf函数。因此,要么包括'stdio.h',要么将CIN和COUT用于I/O操作。

相关文章: