Recursion can be used to do both tasks in one line. Below are one line implementations for stracat() and strcmp().
void my_strcat( char *dest, char *src)
{
(*dest)? my_strcat(++dest, src): (*dest++ = *src++)? my_strcat(dest, src): 0 ;
}
int main()
{
char dest[100] = "geeksfor" ;
char *src = "geeks" ;
my_strcat(dest, src);
printf ( " %s " , dest);
getchar ();
}
|
The function my_strcmp() is simple compared to my_strcmp().
int my_strcmp( char *a, char *b)
{
return (*a == *b && *b == '\0' )? 0 : (*a == *b)? my_strcmp(++a, ++b): 1;
}
int main()
{
char *a = "geeksforgeeks" ;
char *b = "geeksforgeeks" ;
if (my_strcmp(a, b) == 0)
printf ( " String are same " );
else
printf ( " String are not same " );
getchar ();
return 0;
}
|
The above functions do very basic string concatenation and string comparison. These functions do not provide same functionality as standard library functions.
Please write comments if you find the above code incorrect, or find better ways to solve the same problem.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!