#include <strings.h> |
The header file contains declarations (function prototypes of the string manipulation functions
|
char *strcpy( char s1[], char s2[] )
or:
char *strcpy( char *s1, char *s2 ) // Recall that char a[] <==> char *a in C !!!
|
char *strcpy( char s1[], char s2[] )
{
int i = 0;
/* ----------------------------------
'\0' marks the end of the string !
---------------------------------- */
while ( s2[i] != '\0' )
{
s1[i] = s2[i]; // Copy character at position i
i++; // Move to next character
}
s1[i] = '\0'; // Mark the end of the s1 string
return(s1);
}
|
How to run the program:
|
char *strcpy( char *s1, char *s2 )
{
while ( *s2 != '\0' )
*s1++ = *s2++;
*s1 = '\0'; // Mark the end of the s1 string
return(s1);
}
|
char *strcpy( char *s1, char *s2 )
{
char *r = s1; // Save return value
while ( (*s1++ = *s2++) != '\0' );
return(r);
}
|
Explanation:
|
|
How to run the program:
|
int strcmp( char s1[], char s2[] )
or:
int strcmp( char *s1, char *s2 ) // Recall that char a[] <==> char *a in C !!!
|
int strcmp( char s1[], char s2[] )
{
int i = 0;
/* ----------------------------------
'\0' marks the end of the string !
---------------------------------- */
while ( s2[i] != '\0' && s1[i] != 0 )
{
if ( s1[i] != s2[i] ) // If s1 and s2 differ in char i
break; // exit while loop !
i++;
}
/* ----------------------------------------------------------------
If we reach here, then:
1. one or both of s1 and s2 are exhausted !
2. character position i in s1 and s2 are different
---------------------------------------------------------------- */
return s1[i] - s2[i]; // s1[i] - s2[i] will tell us which string
// is lexicographically smaller
// If they are equal, we will get
// '\0' - '\0' = 0
}
|
How to run the program:
|
int strcmp( char *s1, char *s2 )
{
while ( *s1 != '\0' && *s2 != '\0' )
{
if ( *s1 != *s2 )
break;
s1++;
s2++;
}
return( *s1 - *s2 );
}
|
int strcmp( char *s1, char *s2 )
{
while ( *s1 != '\0' && *s2 != '\0' && (*s1 - *s2) == 0 )
{
s1++;
s2++;
}
return( *s1 - *s2 );
}
|
int strcmp( char *s1, char *s2 )
{
int res = 0;
while ( *s1 != '\0' && *s2 != '\0' && ( res = (*s1 - *s2) ) == 0 )
{
s1++;
s2++;
}
return( res );
}
|
How to run the program:
|