一、字符串第二弹:两头堵模式
字符串问题中, 模拟实现strcpy,和strstr 是两大重点,现在介绍第三大重点,两头堵模式,即在形如" abcdefghijklmnopqrstuvwxyz "
的字符串,去掉前后空格, 形成新的字符串,或是求出非空格的字符个数等,都需要用到两头堵模式;
二、举个例子:
对以下字符串," abcdefghijklmnopqrstuvwxyz "
要求去掉空格形成新的字符串,并求出非字符个数;
1、while循环实现
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int isspace1(char p)//判断字符是否为空格
{
if(p==' ')
{
return -1;//若是空格,则返回-1;
}
return 0;//不是空格返回0
}
int getstr(char *mybuf1,char *mybuf2)
{
int ret =0;
int count=0;
char *p= mybuf1;//找一个新的指针,将原mybuf1的数据保存一份
int i=0,j=0;
if(mybuf1==NULL||mybuf2==NULL)//检验实参传过来的空间是否合法
{
ret=-1;
return ret;
}
j=strlen(mybuf1)-1;
while(isspace1(p[i]) && p[i] != '\0')///////////1////////
{
i++;
}
while(isspace1(p[j]) && j>0 )
{
j--;
}/////////////2///////////
count=j-i+1; //非空格字符的个数
memcpy(mybuf2,mybuf1+i,count);//字符串拷贝函数,不拷贝'\0'
mybuf2[count]='\0';//手动在最后一个字符后面加入字符串结束标志'\0'
printf("count=%d\n",count);
return 0;
}
//主调函数
void main()
{
int ret=0;
char *buf1=" abcdefghijklmnopqrstuvwxyz ";
char buf2[100];
ret=getstr(buf1,buf2);
if(ret!=0)//判断是否操作成功
{
printf("func getstr err:(ret!=0),%d\n",ret);
}
else{
printf("新字符串为buf2:%s\n",buf2);
}
system("pause ");
}
三、运行结果:
2、for循环实现,不要isspace()函数
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int isspace1(char p)//判断字符是否为空格
{
if(p==' ')
{
return -1;
}
return 0;
}
int getstr(char *mybuf1,char *mybuf2)
{
int ret =0;
int count=0;
char *p= mybuf1;
int i=0,j=0;
if(mybuf1==NULL||mybuf2==NULL)
{
ret=-1;
return ret;
}
j=strlen(mybuf1)-1;
for(i=0;p[i]==' '&&p[i] != '\0'&&p[j]==' ' && j>0;i++,j--)
{
;
}
count=j-i+1;
memcpy(mybuf2,mybuf1+i,count);//字符串拷贝函数
mybuf2[count]='\0';
printf("count=%d\n",count);
return 0;
}
void main()
{
int ret=0;
char *buf1=" abcdefghijklmnopqrstuvwxyz ";
char buf2[100];
ret=getstr(buf1,buf2);
if(ret!=0)
{
printf("func getstr err:(ret!=0),%d\n",ret);
}
else{
printf("新字符串为buf2:%s\n",buf2);
}
system("pause ");
}
2、运行结果: