1、编程实现strcpy()函数的功能
(1)方法一:
#include<stdio.h> int main(void){ char str1[80] = "abcdefg"; char str2[80]; int i; for(i = 0; str1[i]; i++){ str2[i] = str1[i]; } str2[i] = 0; printf("%s\n", str1); printf("%s\n", str2); return 0; }
(2)、方法二:一行核心代码实现字符串复制
#include<stdio.h> int str_copy(char *str1, char *str2); int str_copy(char *str1, char *str2){ /* for(; *str1; str1++, str2++){ *str2 = *str1; } *str2 = 0; } for(; *str1; ){ *str2++ = *str1++; } *str2 = 0; while((*str2 = *str1) != 0){ str1++; //此时,就不用出循环在赋指为0; str2++; } while((*str2++ = *str1++) != 0); */ if(str1 == NULL || str2 == NULL){ return -1; } while(*str2++ = *str1++); return 0; int main(void){ char str1[80] = "abcdefg"; char str2[80]; //char *str2 = NULL; int ret = 0; ret = str_copy(str1, str2); if(ret != 0){ printf("有一个地址为空,所以有错\n"); }else{ printf("%s\n", str1); printf("%s\n", str2); } return 0; }
运行结果:
2、求子串出现在字符串中的次数
代码如下:
#include<stdio.h> #include<string.h> void strstrCount(char *p, char *q, int *count); void strstrCount(char *p, char *q, int *count){ int c = 0; if(p == NULL || q == NULL){ printf("有地址为空,不能查找子串个数\n"); return; } while(p = strstr(p, q)){ c++; p = p + strlen(q); if(p == NULL){ break; } } *count = c; } int main(void){ char *p = "abc12421abc34345abc325423abc"; char *q = "abc"; int count = 0; strstrCount(p, q, &count); printf("%d\n", count); return 0; }
运行结果:
3、去掉字符串的前后空格
代码如下:
#include<stdio.h> #include<string.h> #include<malloc.h> void trimSpace(char **str1, char *str2); void trimSpace(char **str1, char *str2){ int length = strlen(str2); char *tmp; *str1 = (char *)malloc(sizeof(char)*length); tmp = *str1; for(; *str2; str2++){ if(*str2 != ' '){ *tmp++ = *str2; } } *tmp = 0; } int main(void){ char str[] = " abcdefg "; char *str1; printf("%s\n", str); trimSpace(&str1, str); printf("%s\n", str1); }
运行结果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。