In: Computer Science
Look up the man pages for the following string functions from the C standard library, and write implementations of each:
Please explain the work please, thank you
In C++, std::strstr() is a predefined function used for string handling. string.h is the header file required for string functions.
This function takes two strings s1 and s2 as an argument and finds the first occurrence of the sub-string s2 in the string s1. The process of matching does not include the terminating null-characters(‘\0’), but the function stops there.
Implement in C:
#include <stdio.h>
// returns true if X and Y are same
int compare(const char *X, const char *Y)
{
while (*X && *Y)
{
if (*X != *Y)
return 0;
X++;
Y++;
}
return (*Y == '\0');
}
// Function to implement strstr() function
const char* strstr(const char* X, const char* Y)
{
while (*X != '\0')
{
if ((*X == *Y) &&
compare(X, Y))
return X;
X++;
}
return NULL;
}
// Implement strstr function in C
int main()
{
char *X = "Techie Delight - Coding made easy";
char *Y = "Coding";
printf("%s\n", strstr(X, Y));
return 0;
}
Return Value: This function returns a pointer points to the first character of the found s2 in s1 otherwise a null pointer if s2 is not present in s1. If s2 points to an empty string, s1 is returned.