|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 moc 于 2018-8-16 08:47 编辑
1、练习一:两个辅助指针挖取字符串
题目:有一个字符串符合以下特征(”abcdef,acccd,eeee,aaaa,e3eeeee,sssss,";),要求写一个函数(接口),输出以下结果
1) 以逗号分割字符串,形成二维数组,并把结果传出;
2) 把二维数组行数运算结果也传出。
请自己定义一个接口(函数)。
要求1:能正确表达功能的要求,定义出接口(函数);
要求2:正确实现接口(函数),并实现功能;
要求3:编写正确的测试用例。
- #include "stdio.h"
- #include "stdlib.h"
- #include "string.h"
- int spitString(const char *buf1, const char c, char buf[10][30], int *mycount)
- {
- const char *p = NULL; // const char *p 指向常量的指针,去接受const char*形参
- const char *pTmp = NULL;
- int count = 0;
- int tmpcount = 0;
- pTmp = buf1;
- p = buf1;
- do
- {
- p = strchr(p, c);
- if (p!= NULL) //如果找到
- {
- tmpcount = p - pTmp; //得到挖到字符串的长度
- memcpy(buf[count], pTmp , tmpcount);
- buf[count][tmpcount] = '\0'; // C语言用带'\0'字符数组模拟字符串
- printf("%s \n", buf[count]);
- pTmp = p = p + 1;
- count ++;
- }
- else
- {
- break;
- }
- } while (*p != '\0');
- }
- void main()
- {
- char *p = "abcdef,acccd,eeee,aaaa,e3eeeee,sssss,";
- char c = ',';
- char buf[10][30];
- int ncount;
- spitString(p, c, buf, &ncount);
- system("pause");
- }
复制代码
2、练习二:查找子串出现次数并替换
题目:有一个字符串符合以下特征(” "abcd11111abcd2222abcdqqqqq"”),要求写一个函数(接口),输出以下结果
1) 求字符串字串(“abcd”)出现的次数,并把结果传出;
2) 把字符串替换成(dcba11111dcba 2222dcbaqqqqq),并把结果传出。
请自己定义一个接口(函数)。
要求1:能正确表达接口(函数);
要求2:正确实现接口(函数),并实现功能;
要求3:编写正确的测试用例。
- #include "stdio.h"
- #include "stdlib.h"
- #include "string.h"
- // 交换内存空间
- int memchange(char *p1, char *p2)
- {
- int rev = 0;
- if (p1 == NULL || p2 == NULL)
- {
- rev = -1;
- return rev;
- }
- char c;
- while (p1 < p2)
- {
- c = *p1;
- *p1 = *p2;
- *p2 = c;
- p1++;
- p2--;
- }
- return rev;
- }
- // 查找子串出现的次数,并替换子串
- int getRestbuf(const char*inbuf1, const char *inbuf2, int *count, char *outbuf)
- {
- int rev = 0;
- if (inbuf1 == NULL || inbuf2 == NULL)
- {
- rev = -1;
- return rev;
- }
- char c = inbuf2[0]; //要查找的字符串的首字符
- char findstr[100];
- int len = strlen(inbuf2);
- int outcount = 0 ;
- strcpy(outbuf, inbuf1);
- //printf("%s\n", outbuf);
-
- do
- {
- outbuf = strchr(outbuf, c);
- if (outbuf != NULL) // 如果找到
- {
- memcpy(findstr, outbuf, len);
- findstr[len] = '\0';
- if (strcmp(findstr, inbuf2) == 0)
- {
- outcount++;
- memchange(outbuf, outbuf+len-1);
- }
- outbuf++;
- }
- else
- {
- break;
- }
- }while (*outbuf != '\0');
-
- *count = outcount;
- return rev;
- }
- void main()
- {
- int rev = 0;
- char *strbuf1 = "abcd11111abcd2222abcdqqqqq";
- char *strbuf2 = "abcd" ;
- int str2Count = 0;
- char strout[100];
-
- rev = getRestbuf(strbuf1, strbuf2, &str2Count, strout);
- if (rev != 0)
- {
- printf("fun error, code:%d", rev);
- }
- printf("outstr:%s\ncount:%d\n", strout, str2Count);
- system("pause");
- }
复制代码
|
|