在数组中仅比较一个字符
Comparing only one char in an array
我是新生。
这是我的代码
#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,如果是这种情况,请使用cin
和std::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操作。
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用动态分配将 char* 复制到另一个字符**
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 使用连续分隔符和空最后一个字符进行拆分
- 如何比较文件中包含的下一个字符
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何从文本文件中一次读取一个字符
- 将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
- 读取输入后,输出丢失了一个字符
- 比较最后一个字符,不区分大小写(带谓词?
- 如果一个字符,比如说"9",我减去"0",我在结果上使用 is 数字,我是真还是假
- 为什么 std::istream::gcount 返回的字符比预期的多一个字符
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 在弦乐器中删除最后一个字符