C language implementation of strcmp () and strcpy () functions, strcmpstrcpy
#include <stdio.h>#include <assert.h>char *strcpy(char *strDest, const char *strScr){ char *address = strDest; assert((strDest != NULL) && (strScr != NULL)); while(*strScr) { *strDest++ = *strScr++; } *strDest = '\0'; return address;}int strcmp (const char *str1,const char *str2){ int len = 0; assert((str1 != NULL) && (str2 != NULL)); while(*str1 && *str2 && (*str1 == *str2)) { str1++; str2++; } return *str1-*str2;}void main(){ char str1[]={"Hello"}; char str2[]={"World!"}; printf("%d\n",strcmp(str1,str2)); printf("%s\n",strcpy(str1,str2));}
Output:
Functions of strcmp and strcpy in C Language
Example of strcmp
/* STRCMP. C */
# Include <string. h>
# Include <stdio. h>
Char string1 [] = "The quick brown dog jumps over the lazy fox ";
Char string2 [] = "The QUICK brown dog jumps over the lazy fox ";
Void main (void)
{
Char tmp [20];
Int result;
/* Case sensitive */
Printf ("Compare strings: \ n \ t % s \ n", string1, string2 );
Result = strcmp (string1, string2 );
If (result> 0)
Strcpy (tmp, "greater ");
Else if (result <0)
Strcpy (tmp, "less ");
Else
Strcpy (tmp, "equal ");
Printf ("\ tstrcmp: String 1 is % s string 2 \ n", tmp );
/* Case insensitive (cocould use equivalent _ stricmp )*/
Result = _ stricmp (string1, string2 );
If (result> 0)
Strcpy (tmp, "greater ");
Else if (result <0)
Strcpy (tmp, "less ");
Else
Strcpy (tmp, "equal ");
Printf ("\ t_stricmp: String 1 is % s string 2 \ n", tmp );
}
Output
Compare strings:
The quick brown dog jumps over the lazy fox
The QUICK brown dog jumps over the lazy fox
Strcmp: String 1 is greater than string 2
_ Stricmp: String 1 is equal to string 2
Example of Strcpy
/* STRCPY. C: This program uses strcpy
* And strcat to build a phrase.
*/
# Include <string. h>
# Include <stdio. h>
Void main (v ...... remaining full text>
The functions of strcat, strcpy, strcmp, and strlen can be implemented using a C language program and a user-defined function.
Char * mystrcat (char * dst, char * src)
{
Char * p = dst;
While (* p) ++ p;
While (* p ++ = * src ++ );
Return dst;
}
Char * mystrcpy (char * dst, char * src)
{
While (* dst ++ = * src ++ );
Return dst;
}
Int mystrcmp (char * dst, char * src)
{
While (* dst & * dst = * src)
{
++ Dst;
++ Src;
}
Return * dst-* src;
}
Int mystrlen (char * dst)
{
Char * p = dst;
While (* p) ++ p;
Return p-dst;
}
Int main ()
{
Char s [32], t [32] = "HELLO, CHINA ";
Mystrcpy (s, "HELLO ,");
Puts (s );
Mystrcat (s, "USA ");
Puts (s );
Printf ("% d \ n", mystrlen (s), mystrcmp (s, t ));
}