【发布时间】:2022-11-10 14:09:17
【问题描述】:
这是代码:
#define _GNU_SOURCE
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
string alphabet = "abdcefghijklmnopqrstuvwxyz";
string text = "world";
string ciphertext = "";
for(int i = 0; i < strlen(text); i++)
{
ciphertext = strstr(alphabet, &text[i]);
printf("%s \n", ciphertext);
}
它输出以下结果:
(null)
(null)
(null)
(null)
dcefghijklmnopqrstuvwxyz
所以看起来 strstr() 仅适用于最后一个字符,在本例中为“d”。 为什么它不适用于先前的字符? strcasestr() 具有相同的行为
【问题讨论】:
-
strstr返回一个指向匹配子字符串的指针,或NULL,如手册页所述。在这些字符串"world""orld""rld""ld"和"d"中,只有最后一个是alphabet的子字符串。 -
此外,
alphabet字母序列中存在拼写错误。 -
你期望什么输出?顺便说一句:不要输入硬编码的字母,而是让您的程序构建它。计算机不会像您那样出错。