**题目3
函数ReadDat( )实现从文件IN.DAT中读取一篇英文文章存入到字符串数组xx中;请编制函数StrOR( ),其函数的功能是:以行为单位依次把字符串中所有小写字母o左边的字符串内容移到该串的右边存放,然后把小写字母o删除,余下的字符串内容移到已处理字符串的左边存放,之后把已处理的字符串仍按行重新存入字符串数组xx中。最后main()函数调用函数WriteDat()把结果xx输出到文件OUT5.DAT中。
例如:原文:n any field.Yu can create an index
you have the correct record.
结果:n any field. Yu can create an index
rd. yu have the crrect rec
原始数据文件存放的格式是:每行的宽度均小于80个字符,含标点符号和空格。
注意:部分源程序存放在文件prog1.c中。
请勿改动主函数main()、读数据函数ReadDat()和输出数据函数WriteDat()的内容。
#include
#include
#include
char xx[50][80] ;
int maxline = 0 ; /* 文章的总行数 */
int ReadDat(void) ;
void WriteDat(void) ;
void StrOR(void)
{int i,righto,j,s,k;
char tem[80];
for(i=0;i
for(j=strlen(xx[i])-1;j>=0;j--)
{ k=0;
memset(tem,0,80); /*初始化字符串数组tem*/
if(xx[i][j]=='o‘) /*如果当前字符为'o',进入以下语句*/
{righto=j; /*则将此字符中位置j的值赋给righto*/
for(s=righto+1;s
tem[k++]=xx[i][s]; /*从righto的下一跳开始将其后所有的字符都存入到tem中*/
for(s=0;s
if(xx[i][s]!='o‘) tem[k++]=xx[i][s]; /*将不是字符'o’的字符全存入到tem中*/
strcpy(xx[i],tem); /*将当前已处理的字符重新存入当前行xx*/
}
else continue;
}
}
void main()
{
clrscr() ;
if(ReadDat()) {
printf(“数据文件IN.DAT不能打开!\n\007”) ;
return ;
}
StrOR() ;
WriteDat() ;
}
int ReadDat(void)
{
FILE *fp ;
int i = 0 ;
char *p ;
if((fp = fopen(“IN.DAT”, “r”)) == NULL) return 1 ;
while(fgets(xx[i], 80, fp) != NULL) {
p = strchr(xx[i], '\n‘) ;
if(p) *p = 0 ;
i++ ;
}
maxline = i ;
fclose(fp) ;
return 0 ;
}
void WriteDat(void)
{
FILE *fp ;
int i ;
clrscr() ;
fp = fopen(“OUT5.DAT”, “w”) ;
for(i = 0 ; i < maxline ; i++) {
printf(“%s\n”, xx[i]) ;
fprintf(fp, “%s\n”, xx[i]) ;
}
fclose(fp) ;
}
解法二:
void StrOR(void)
{ int i;
char a[80],*p;
for(i=0;i
{ p=strchr(xx[i],'o’);
while(p)
{ memset(a,0,80);
memcpy(a,xx[i],p-xx[i]);
strcpy(xx[i],p+1);
strcat(xx[i],a);
p=strchr(xx[i],'o‘);
}
}
}
解法三:
void StrOR(void)
{ int i,j; char yy[80],*p;
for(i=0; i
for(j=0; j
if(xx[i][j]=='o’)
{ p=&xx[i][j+1];
strcpy(yy,p); /*将指针p所指向的字符串拷贝到字符串yy中去*/
strncat(yy,xx[i],j); /*将字符串xx[i]中前j个字符连接到yy中*/
strcpy(xx[i],yy); /*将字符串yy重新拷贝到字符串xx[i]中去*/
j=0; /* 开始下一次的扫描。*/
}
}
相关库函数解释:
char *strncat(char *dest, const char *src, size_t maxlen)
功能:将字符串src中前maxlen个字符连接到dest中
相关头文件:string.h
char *strcpy(char *dest, const char *src)
功能:将字符串src拷贝到字符串dest中去
相关头文件:string.h