我使用以下代码测试我收到的电子邮件文件中的一些文本检测。
#include <stdio.h>
int main()
{
int max_size = 100;
char email[100] ="aheanstring4strinstringzil.comg";
int pointer = 0;
int i = 1;
int j = 0;
int len = 0;
int chk = 0;
char found1[7] = "string1";
char found2[7] = "string2";
char found3[7] = "string3";
char found4[7] = "string4";
char found5[7] = "string5";
char user1[7] = "string1"; // 23
char user2[7] = "string2";// 19
char user3[7] = "string3"; // 14
char user4[7] = "string4"; // 16
char user5[7] = "string5";; // 15
while (pointer != max_size && chk != 1)
{
for (j = 0;j<7; j++)
{
found1[j] = *(email+pointer+j);
}
if (strcmp(found1, user1) == 0){
printf("Authorized User Found\n");
chk = 1;
continue;
}
for (j = 0;j<7; j++)
{
found2[j] = *(email+pointer+j);
}
if (strcmp(found2, user2) == 0){
printf("Authorized User Found\n");
chk = 1;
continue;
}
for (j = 0;j<7; j++)
{
found3[j] = *(email+pointer+j);
}
if (strcmp(found3, user3) == 0){
printf("Authorized User Found\n");
chk = 1;
continue;
}
for (j = 0;j<7; j++)
{
found4[j] = *(email+pointer+j);
}
if (strcmp(found4, user4) == 0){
printf("Authorized User Found\n");
chk = 1;
continue;
}
for (j = 0;j<7; j++)
{
found5[j] = *(email+pointer+j);
}
if (strcmp(found5, user5) == 0){
printf("Authorized User Found\n");
chk = 1;
continue;
}
pointer++;
}
printf("Check is %d, Pointer is %d\n",chk, pointer);
return 0;
}
我使用上面的代码在电子邮件正文中查找特定用户。如果找到用户,while 循环就会中断。当我尝试运行它时,我在上面的变量 (email) 中包含了不同的字符串
我尝试先在不同的在线 C 编译器上运行它。他们所有人的字符串 1、3 和 5 都工作正常。 (被检测到)
其中一些字符串 2 工作正常(被检测到)。
然而,他们所有人都知道 string2 从未被检测到。我不知道为什么。我试着想一个原因,但想不通。
非常感谢您的帮助。
最佳答案
char found1[7] = "string1";
此处 found1
不是 C 中的有效字符串,因为没有 nul 终止。你需要有
char found1[8] = "string1";
您将 found1
传递给 strcmp()
,这将导致未定义的行为,因为 strcmp()
需要一个空终止字符串。
或者像@Barak Manos建议的那样
char found1[] = "string1";
关于c - 字符串比较差异(适用于某些情况,有时无效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30639122/