★☆題目3(上機(jī)題庫id 133題;上機(jī)題庫id 59、99字符串位置倒置題)
函數(shù)readdat( )實(shí)現(xiàn)從文件in.dat中讀取一篇英文文章存入到字符串?dāng)?shù)組中;請編制函數(shù)stror( ),其函數(shù)的功能是:以行為單位依次把字符串中所有小寫字母o左邊的字符串內(nèi)容移到該串的右邊存放,然后把小寫字母o刪除,余下的字符串內(nèi)容移到已處理字符串的左邊存放,之后把已處理的字符串仍按行重新存入字符串?dāng)?shù)組中。最后main()函數(shù)調(diào)用函數(shù)writedat()把結(jié)果輸出到文件out5.dat中。
例如:原文:n any field.yu can create an index
you have the correct record.
結(jié)果:n any field. yu can create an index
rd. yu have the crrect rec
原始數(shù)據(jù)文件存放的格式是:每行的寬度均小于80個(gè)字符,含標(biāo)點(diǎn)符號(hào)和空格。
注意:部分源程序存放在文件prog1.c中。
請勿改動(dòng)主函數(shù)main()、讀數(shù)據(jù)函數(shù)readdat()和輸出數(shù)據(jù)函數(shù)writedat()的內(nèi)容。
#include <stdio.h>
#include <string.h>
#include <conio.h>
char [50][80] ;
int maxline = 0 ; /* 文章的總行數(shù) */
int readdat(void) ;
void writedat(void) ;
void stror(void)
{int i,righto,j,s,k;
char tem[80];
for(i=0;i<maxline;i++) /*倒序循環(huán)*/
for(j=strlen([i])-1;j>=0;j--)
{ k=0;
memset(tem,0,80); /*初始化字符串?dāng)?shù)組tem*/
if([i][j]=='o') /*如果當(dāng)前字符為'o',進(jìn)入以下語句*/
{righto=j; /*則將此字符中位置j的值賦給righto*/
for(s=righto+1;s<strlen([i]);s++)
tem[k++]=[i][s]; /*從righto的下一跳開始將其后所有的字符都存入到tem中*/
for(s=0;s<righto;s++) /*從當(dāng)前行首部開始到出現(xiàn)字符'o'的位置(righoto)之前開始循環(huán)*/
if([i][s]!='o') tem[k++]=[i][s]; /*將不是字符'o'的字符全存入到tem中*/
strcpy([i],tem); /*將當(dāng)前已處理的字符重新存入當(dāng)前行/
}
else continue;
}
}
void main()
{
clrscr() ;
if(readdat()) {
printf("數(shù)據(jù)文件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([i], 80, fp) != null) {
p = strchr([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", [i]) ;
fprintf(fp, "%s\n", [i]) ;
}
fclose(fp) ;
}
解法二:
void stror(void)
{ int i;
char a[80],*p;
for(i=0;i<maxline;i++)
{ p=strchr([i],'o');
while(p)
{ memset(a,0,80);
memcpy(a,[i],p-[i]);
strcpy([i],p+1);
strcat([i],a);
p=strchr([i],'o');
}
}
}
解法三:
void stror(void)
{ int i,j; char yy[80],*p;
for(i=0; i<maxline;i++)
for(j=0; j<strlen([i]); j++)
if([i][j]=='o')
{ p=&[i][j+1];
strcpy(yy,p); /*將指針p所指向的字符串拷貝到字符串yy中去*/
strncat(yy,[i],j); /*將字符串[i]中前j個(gè)字符連接到y(tǒng)y中*/
strcpy([i],yy); /*將字符串yy重新拷貝到字符串[i]中去*/
j=0; /* 開始下一次的掃描。*/
}
}
相關(guān)庫函數(shù)解釋:
char *strncat(char *dest, const char *src, size_t maxlen)
功能:將字符串src中前maxlen個(gè)字符連接到dest中
相關(guān)頭文件:string.h
char *strcpy(char *dest, const char *src)
功能:將字符串src拷貝到字符串dest中去
相關(guān)頭文件:string.h