字符串操作的实现:strstr、strcat、strcmp和stcpy
2015-08-27 15:02
459 查看
几个重点强调一下:
(1)注意使用assert;
(2)strcat 和 strcpy最后注意赋值'\0';
(3)strcpy注意内存覆盖的情况;
(4)strcmp中:while(!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2 != '\0');???为什么要转换类 型;
(5)strstr函数中返回的类型也要为const。
(1)注意使用assert;
(2)strcat 和 strcpy最后注意赋值'\0';
(3)strcpy注意内存覆盖的情况;
(4)strcmp中:while(!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2 != '\0');???为什么要转换类 型;
(5)strstr函数中返回的类型也要为const。
#include<stdio.h> #include<assert.h> #include<string.h> const char* strstr(const char *s1, const char *s2) { assert(s1 != NULL && s2 != NULL); const char *tmp = s1; for(; *tmp != '\0'; ++tmp) { const char *result = tmp; const char *tmp1 = s2; while(*result == *tmp1 && *tmp1 != '\0') { ++result; //++tmp; ++tmp1; } if(*tmp1 == '\0') return tmp; //return result } return NULL; } char *strcat(char *dest, const char *src) { assert(dest != NULL || src != NULL); char *tmp = dest; while(*tmp != '\0') { ++tmp; } while(*src != '\0') { *tmp = *src; ++tmp; ++src; } *tmp = '\0'; return dest; } char *strcpy(char *dest, const char *src) { assert(dest != NULL || src != NULL); int length = strlen(src); char *result = dest; if(dest < src || src + length < dest) { while(*src != '\0') { *dest = *src; ++src; ++dest; } *dest = '\0';//不能忘了 }else { src = src + length - 1; dest = dest + length; *dest = '\0'; --dest; for(int i = 0; i < length; ++i) { *dest = *src; --src; --dest; } } return result; } int strcmp(const char *s1, const char *s2) { assert(s1 != NULL || s2 != NULL); int ret = 0; while(!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2 != '\0') { ++s1; ++s2; } if(ret < 0) return -1; else if(ret > 0) return 1; return ret; } int main() { char s1[] = "shui huai li"; char s2[] = "huai"; char s3[] = "i am the best"; char s4[] = "sorry"; char s6[] = "sorryhe"; char s5[] = "hello world"; const char *result = strstr(s1, s3); if(result) printf("%s\n", result); else printf("i am sorry!!!\n"); //printf("%s\n", strcat(s1, s5)); //printf("%s\n", strcpy(s2, s1)); //printf("%d\n", strcmp(s4, s6)); return 0; }
相关文章推荐
- 数据库链接字符串查询网站
- Flex字符串比较 还有Flex字符串操作
- Ruby中创建字符串的一些技巧小结
- ASP下经常用的字符串等函数参考资料
- 将字符串小写转大写并延时输出的批处理代码
- 将字符串转换成System.Drawing.Color类型的方法
- Lua源码中字符串类型的实现
- Lua性能优化技巧(四):关于字符串
- 字符串聚合函数(去除重复值)
- Ruby中的字符串编写示例
- 总结的5个C#字符串操作方法分享
- sqlserver中求字符串中汉字的个数的sql语句
- sql server字符串非空判断实现方法
- VBS的字符串及日期操作相关函数
- C#实现将千分位字符串转换成数字的方法
- jquery 删除字符串最后一个字符的方法解析
- PowerShell实现在字符串中查找大写字母
- PowerShell中使用Out-String命令把对象转换成字符串输出的例子
- PowerShell中字符串使用单引号和双引号的区别
- Powershell小技巧之获取字符串的行数