Home > Software engineering >  Why strcasestr or (strstr) function outputs (null)?
Why strcasestr or (strstr) function outputs (null)?

Time:10-21

here is the code:

#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);
}

It outputs the following result:

(null) 
(null) 
(null) 
(null) 
dcefghijklmnopqrstuvwxyz 

So it looks like strstr() works only for the last character, in this case "d". Why it does not work for prior characters? strcasestr() has the same behavior

CodePudding user response:

strstr looks for a string in another string. In C, a string is an array of characters, terminated by a NUL character. The first time through your loop, you are calling strstr with a pointer to the w in world, so the string you are telling it to search for is world, which does not appear in your alphabet. Then the loop goes on to search for orld, rld, etc, none of which occur in the alphabet string, until it eventually gets to just d, which it finds.

CodePudding user response:

Because you want to find character in the string, not string in the string, you need to use strchr function:

for(size_t i = 0; text[i]; i  )
{
     ciphertext = strchr(alphabet, text[i]);
     printf("%s \n", ciphertext);
}
  1. Use the correct type for indexes (size_t)
  2. You do not have to call strlen on every iteration. It is enough to check if you did not reach the null terminating character.
  • Related