C语言习题(1)——字符串拷贝,去空格,奇偶抽取字符串

xiaoxiao2021-02-28  119

1.字符串拷贝

/*** 作者:一叶扁舟 作用:字符串的拷贝 时间:18:25 2017/5/1 ***/ #include <stdio.h> #include <string.h> #include <stdlib.h> int copyStr(char *from, char *to){ if (from == NULL || to == NULL){ return -1; } while (*from != '\0'){ *to = *from; from++; to++; } *to = '\0'; return 1; } int main(){ char buf1[100]; char buf2[100]; strcpy(buf1, "abcdefgh"); int temp = copyStr(buf1,buf2); if (temp != 1){ printf("出错了!"); } else{ printf("%s", buf2); } printf("\n"); system("pause"); return 0; }

2.字符串去除空格

/** 1、有一个字符串开头或结尾含有n个空格(” abcdefgdddd ”),欲去掉前后空格,返回一个新字符串。 要求1:请自己定义一个接口(函数),并实现功能; 要求2:编写测试用例。 int trimSpace(char *inbuf, char *outbuf); **/ /*** 作者:一叶扁舟 作用: 时间:19:55 2017/5/4 ***/ #include <stdio.h> #include <stdlib.h> #include <string.h> int trimSpace2(char *inbuf, char *outbuf){ char * result = outbuf; if (inbuf == NULL || outbuf == NULL){ return -1; } while (*inbuf != '\0'){ if (*inbuf == ' '){ inbuf++; } else{ *result = *inbuf; result++; inbuf++; } } *result = '\0'; return 1; } void main(){ char buff1[100] = " abcdefgdddd "; char buff2[100] = {0}; trimSpace2(buff1,buff2); printf("%s",buff2); printf("\n"); system("pause"); }

3.抽取奇偶字符串

/** 2、有一个字符串”1a2b3d4z”,; 要求写一个函数实现如下功能, 功能1:把偶数位字符挑选出来,组成一个字符串1 功能2:把奇数位字符挑选出来,组成一个字符串2 功能3:把字符串1和字符串2,通过函数参数,传送给main,并打印。 功能4:主函数能测试通过。 int getStr1Str2(char *souce, char *buf1, char *buf2); */ /*** 作者:一叶扁舟 作用: 时间:20:28 2017/5/4 ***/ #include <stdio.h> #include <stdlib.h> #include <string.h> int getStr1Str2(char *souce, char *buf1, char *buf2){ if (souce == NULL || buf1 == NULL || buf2 == NULL){ return -1; } char *p1 = buf1; char *p2 = buf2; int i = 1; while (*souce != '\0'){ //偶数 if (i % 2 == 0){ *p1 = *souce; souce++; p1++; }else{//奇数 *p2 = *souce; souce++; p2++; } i++; } return 1; } void main(){ char buff1[100] = "a1b2c3d4e5f6g"; char buff2[100] = { 0 }; char buff3[100] = { 0 }; int temp = getStr1Str2(&buff1, &buff2, &buff3); if (temp != -1){ printf("偶数数据:\n%s\n", buff2); printf("奇数数据:\n%s\n", buff3); } else{ printf("查取数据错误\n"); } system("pause"); }
转载请注明原文地址: https://www.6miu.com/read-82813.html

最新回复(0)