【1】字符串比较函数如何实现?
函数原型:int mystrcmp(const char *src,const char *dst)
小于返回值:-1
等于返回值:0
大于返回值:1
(1)第一种实现代码如下:
1 int mystrcmp(const char *src, const char *dst) 2 { 3 int ret = 0; 4 while (!(ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst) 5 { 6 ++src; 7 ++dst; 8 } 9 if (ret < 0) 10 ret = -1; 11 else if (ret > 0) 12 ret = 1; 13 14 return ret; 15 }
(2)第二种实现代码如下:
1 #include <iostream> 2 using namespace std; 3 4 int strcmp(const char *si, const char *sd) 5 { 6 int k; 7 while ((k = *si - *sd) == 0 && *si++ && *sd++); 8 return k; 9 } 10 11 void main() 12 { 13 char * str1 = "abcdef"; 14 char * str2 = "abcgef"; 15 char * str3 = "abccef"; 16 char * str4 = "abcdef"; 17 cout << strcmp(str1, str2) << endl; // -3 18 cout << strcmp(str1, str3) << endl; // 1 19 cout << strcmp(str1, str4) << endl; // 0 20 }
Good Good Study, Day Day Up.
顺序 选择 循环 总结