★☆題目3(上機題庫id 133題;上機題庫id 59、99字元串位置倒置題)
函式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 <stdio.h>
#include <string.h>
#include <conio.h>
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<maxline;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<strlen(xx[i]);s++)
tem[k++]=xx[i][s]; /*從righto的下一跳開始將其後所有的字元都存入到tem中*/
for(s=0;s<righto;s++) /*從當前行首部開始到出現字元'o'的位置(righoto)之前開始循環*/
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<maxline;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<maxline;i++)
for(j=0; j<strlen(xx[i]); 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