编写一个字符串处理程序,用C/C++,急!!!谢谢~~~

1.程序包括:主函数、输入字符串函数、查找字符串函数、字符串切分函数。
2. “输入字符串函数”中要求输入两个字符串,第一个用gets()函数输入,第二个用getchar()函数输入。
3.“查找字符串函数”的功能是,在第一个字符串中查找第二个字符串,函数返回第二个字符串在第一个字符串中第一个字符的下标。
4.“字符串切分函数”的功能是:在第一个字符串中的第二个字符串前后各插入一个空格。
5. 在主函数中先调用“输入字符串函数”,然后调用“字符串切分函数”,在“字符串切分函数”中调用“查找字符串函数”,利用查找结果完成切分。

没有使用字符串库函数。
#include <cstdlib>
#include<iostream>
#include<stdlib.h>
#define DB if(debug==1)
using namespace std;
char *getstr1(char * buf);
char *getstr2(char * buf);
int index(char*str,char*sub);
char* cut(char*str1,char*sub);
int debug;
int endp;
int main(int argc, char *argv[])
{ debug=1;
endp=0;
char *buf1=(char*)malloc(512);
getstr1(buf1);

char *buf2=(char*)malloc(512);

getstr2(buf2);

DB {
cout<<"debug main::\n";
cout<<"str: "<<buf1<<endl;
cout<<"sub: "<<buf2<<endl;
cout<<"index="<<index(buf1,buf2);
cout<<"end debug";
}
cut(buf1,buf2);
cout<<buf1;
system("PAUSE");

free(buf1);
free(buf2);
return EXIT_SUCCESS;
}

char *getstr1(char * buf){
return gets(buf);

}
char *getstr2(char * buf){
char c;
int p=0;
while ((c=getchar())!= '\n' ){

buf[p++]=c;

}
buf[p]='\0';

return buf;
}
int index(char*str,char*sub){
int p=0;
int r=0;
while (1){
DB { cout<<"r="<<r<<endl;
}
if(!str[r])return -1;
p=0;
while(1){
if(sub[p]==0){endp=r+p;return r;}
if(sub[p]!=str[r+p]) break;
p++;
}
r++;

}
return -1;
}
char* cut(char*str1,char*sub){
int pos=index(str1,sub);
char *buf=(char*)malloc(512);
if (pos==-1) return str1;
int i=0,p=pos;
while(buf[i]=str1[endp+i]) i++;
i=0;
str1[p++ +i]=' ';
while(str1[p+i]=sub[i]) i++;
str1[p+i++]=' ';
p=p+i;i=0;
while(str1[p+i]=buf[i])i++;
free (buf);
return str1;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-05-09
#include <stdio.h>
#include <string.h>

void input(char *str1, char *str2)
{
int c;
gets(str1);
while((c = getchar()) != '\n')
*str2++ = c;
*str2 = '\0';
}

int find(char *str1, char *str2)
{
char *p = strstr(str1, str2);

if(p == NULL)
return -1;
else
return p - str1;
}

void split(char *str1, char *str2)
{
char *p,*q;
char tmp[300];
char *ptmp;
int i;
int len = strlen(str2);

ptmp = tmp;
p = str1;
q = str2;
while((i = find(p, q)) != -1)
{
strncpy(ptmp, p, i);
ptmp += i;
*ptmp++ = ' ';
strcpy(ptmp, q);
ptmp += len;
*ptmp++ = ' ';
p += i + len;
}
strcpy(ptmp, p);
strcpy(str1, tmp);
}

int main()
{
char str1[300];
char str2[300];

input(str1, str2);
split(str1, str2);
printf("%s\n",str1);

return 0;
}
第2个回答  2012-05-09
dfdfdf
相似回答