您好,登錄后才能下訂單哦!
1、編程實(shí)現(xiàn)strcpy()函數(shù)的功能
(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)、方法二:一行核心代碼實(shí)現(xiàn)字符串復(fù)制
#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++; //此時(shí),就不用出循環(huán)在賦指為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("有一個(gè)地址為空,所以有錯(cuò)\n"); }else{ printf("%s\n", str1); printf("%s\n", str2); } return 0; }
運(yùn)行結(jié)果:
2、求子串出現(xiàn)在字符串中的次數(shù)
代碼如下:
#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("有地址為空,不能查找子串個(gè)數(shù)\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; }
運(yùn)行結(jié)果:
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); }
運(yùn)行結(jié)果:
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。