You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何strstr/strcasestr函数返回(null)?仅匹配最后一个字符

strstr仅匹配最后一个字符的原因分析

原代码

#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函数的用法理解有误:

  • strstr(str1, str2)的作用是在str1中查找完整的str2子串(以'\0'结尾的字符序列),而非单个字符。
  • 你传入的&text[i]不是单个字符,而是从text[i]位置开始到字符串末尾的整个后缀:
    • 当i=0时,&text[0]是字符串"world",alphabet中不存在该子串,返回NULL;
    • 当i=1时,&text[1]是"orld",同样不在alphabet中,返回NULL;
    • ...以此类推,直到i=4时,&text[4]是单字符字符串"d"(末尾自带'\0'),刚好能在alphabet中匹配到,因此返回对应位置的指针。

修正方案

如果需求是查找单个字符在alphabet中的位置,推荐使用专门的单字符查找函数strchr(区分大小写),代码如下:

#define _GNU_SOURCE
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

string alphabet = "abdcefghijklmnopqrstuvwxyz";
string text = "world";
char* ciphertext = NULL;

for(int i = 0; i < strlen(text); i++)
{
     ciphertext = strchr(alphabet, text[i]);
     printf("%s \n", ciphertext ? ciphertext : "(null)");
}

如果一定要用strstr实现单字符查找,需要构造一个合法的单字符字符串:

#define _GNU_SOURCE
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

string alphabet = "abdcefghijklmnopqrstuvwxyz";
string text = "world";
string ciphertext = "";
char temp[2] = {0}; // 存储单个字符+结束符

for(int i = 0; i < strlen(text); i++)
{
     temp[0] = text[i];
     ciphertext = strstr(alphabet, temp);
     printf("%s \n", ciphertext);
}

内容的提问来源于stack exchange,提问作者Anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:31:08