【问题标题】:Why strcasestr or (strstr) function outputs (null)?为什么 strcasestr 或 (strstr) 函数输出 (null)?
【发布时间】: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 字母序列中存在拼写错误。
  • 你期望什么输出?顺便说一句:不要输入硬编码的字母,而是让您的程序构建它。计算机不会像您那样出错。

标签: c cs50 strstr


【解决方案1】:

strstr 在另一个字符串中查找一个字符串。在 C 中,字符串是一个字符数组,以 NUL 字符结尾。第一次通过你的循环,你调用strstr 并带有指向world 中的w 的指针,所以你告诉它搜索的字符串是world,它不会出现在你的字母表中。然后循环继续搜索orldrld 等,这些都没有出现在字母字符串中,直到它最终到达它找到的d

【讨论】:

    【解决方案2】:

    因为你想找到特点在字符串中,不是字符串中的字符串,你需要使用strchr函数:

    for(size_t i = 0; text[i]; i++)
    {
         ciphertext = strchr(alphabet, text[i]);
         printf("%s 
    ", ciphertext);
    }
    
    1. 为索引使用正确的类型 (size_t)
    2. 您不必在每次迭代时都调用strlen。检查您是否没有到达空终止字符就足够了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 2017-04-26
      • 2018-02-04
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多