主调函数分配内存块;在被调用函数中使用;
//写一个函数,;写一个主函数,用被调用函数,求出字符串1.在字符串2中间出现过几次!
#define _CRT_SECURE_NO_WARNINGS
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
char mycount(char *myp, char *mysub, int *n)
{
int ret = 1;
if (myp == NULL || mysub == NULL||n==NULL)
{
ret = -1;
printf("func mycount() err %d (myp == NULL || mysub == NULL||n==NULL) ",ret);
return ret;
}
char *Myp = myp;
char *Mysub = mysub;
do
{
Myp = strstr(Myp, Mysub);
if (Myp != NULL)
{
(*n)++; //要把所在地址的值取出来++
Myp = Myp + strlen(Mysub);
}
else
{
break;
}
} while (*Myp != '\0');
return ret;
}
void main()
{
char *sub = "abcd";
int n = 0;
char *p = "adiabcd11122abcdqqqabcd1";
mycount(p, sub, &n);//传入函数;
printf("一共出现几次%d",n);
system("pause");
}
在写一个内存模型两头堵
#define _CRT_SECURE_NO_WARNINGS
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
#include<ctype.h>
/*
有一个字符串开头或结尾含有n个空格(" abcdefgddddd "),欲去掉前后空格,返回一个新字符串;
要求1:请自己定义一个接口(函数),并实现功能;
要求2;编写测试用例;
int trimspace(char *inbuf,char *outbuf)
*/
//不调用函数;
void main()
{
int count=0;
int i = 0;
int j = 0;
char p[40] = " abcd ";
char p2[40];
j = strlen(p) -1;// 算出有下标 -1 是因为 下标从0开始。
while (isspace(p[i]) && p[i] != '\0')
{
i++;
}
while (isspace(p[j]) && p[j] != '\0')
{
j--;
}
count = j - i+1;//因为下标从0开始 所以当然少了一个。所以要加上1
//mencpy 从第二个内存首地址开始,拷贝数据拷到前面第一个内存,大小烤N, 返回出来是第一个内存块的首address
memcpy(p2, p+i, count); //里面千万不能写p[i]这个小错。我找了大半天的。他妹的。
p2[count] = '\0';
printf("\n%s",p2);
system("pause");
}
//调用函数
/*
int trimSpace_better( const char *myBuf, char *outBuf)
{
int retVal = 0;
//指针变量为空,返回-1;
if (myBuf == NULL || outBuf==NULL)
{
return -1;
}
//指针变量变量不为空,但是指针指向的字符串为空的,就返回-2
const char *p = myBuf;
int i = 0;
int j = strlen(p) - 1;
while (isspace(p[i]) && p[i] != '\0')
{
i++;
}
while (isspace(p[j]) && p[j] >=0)
{
j--;
}
int count = j - i + 1;//因为下标从0开始 所以当然少了一个。所以要加上1
memcpy(outBuf, p + i, count);
outBuf[count] = '\0';
return retVal;
}
int main()
{
int retVal = 0;
char buf[100] = " abcd1111cdeadsf ";
char bufOut[100];
//char *p=" abcd1111cdeadsf ";
retVal = trimSpace_better(buf, bufOut);
if (retVal != 0)
{
printf("func trimSpace()err ;%d ", retVal);
return 0;
}
printf("%s\n", bufOut);
system("pause");
}
*/
字符串两头堵的模型就是去掉两边空格,已经字符串1,在字符串2出现的次数,不修改输入。
最新推荐文章于 2023-01-02 20:23:48 发布