Library functions for C-language string operations
# Include
// Evaluate the string length (version 1) // use a character array to implement int mystrlen1 (char s []) {int len = 0; while (s [len]! = '\ 0') {len ++;} return len ;}// evaluate the string length (version 2) // use a character pointer to implement int mystrlen2 (char * s) {int len = 0; while (* s! = '\ 0') {len ++; s ++;} return len ;}int main () {char str [] = "hello "; int n = mystrlen1 (str); printf ("% d \ n", n); int m = mystrlen2 (str); printf ("% d \ n", m ); return 0 ;}
# Include
// String copy (version 1) // use an array to implement void mystrcpy1 (char s [], char t []) {int I = 0; while (s [I] = t [I])! = '\ 0') // assign a value first, and then compare whether it is a string Terminator {I ++ ;}// copy a string (version 2) // use a pointer to implement void mystrcpy2 (char * s, char * t) {while (* s = * t )! = '\ 0') {s ++; t ++ ;}// string copy (version 3) // void mystrcpy (char * s, char * t) {while (* s ++ = * t ++); // a non-zero in C indicates logical truth, so you don't need to compare it with '\ 0'} int main () {char a [] = "hello"; char B [100], c [100]; mystrcpy1 (B, a); printf ("% s \ n", B); mystrcpy2 (c, a); printf ("% s \ n", c); return 0 ;}
# Include
// String comparison version 1 // use an array to implement int mystrcmp1 (char s [], char t []) {int I; for (I = 0; s [I] = t [I]; I ++) {if (s [I] = '\ 0') {return 0 ;}} return s [I]-t [I];} // string comparison version 2 // use a character pointer to implement int mystrcmp2 (char * s, char * t) {while (* s = * t) {if (* s = * t) {return 0;} s ++; t ++ ;} return * s-* t;} int main () {char s1 [] = "hello", s2 [] = "Java"; printf ("% d \ n ", mystrcmp1 (s1, s2)> 0? 1:-1); printf ("% d \ n", mystrcmp2 (s1, s2)> 0? 1:-1); return 0 ;}