1.编写函数void FindWord(char *a)。其功能是:将a指向的字符串中最长的单词(空格作为单词分隔符)移动到该字符串的最后。编写main函数,用测试数据中给出的字符串调用函数FindWord,将结果字符串保存到结果文件myf2.out中。例如,测试数据为"you are student too.",则输出结果为 you are too.student。
#include <stdio.h>
#include <string.h>
struct Word
{
char word[25];
int len;
int b;
int e;
}
Word1[150];
int count=0;
int len;
int isc(char t) //判断一个字符是不是字母
{
if((t<='z'&&t>='a')||(t<='Z'&&t>='A'))
return 1;
else
return 0;
}
int isw(char t[],int b,int e)//判断字符串从下标b开始到下标e是不是一个单词
{
int flag=1;
for(int i=b; i<=e; i++)//下标b开始到下标e,中间有不是字母的,返回
{
if(isc(t[i])==0)
{
return 0;
}
}
if(b>0)//不是字符串第一个字符
{
if(isc(t[b-1])==0&&isc(t[e+1])==0)//下标b-1和下标e+1不是字母,返回
{
return 1;
}
}
else
{
if(isc(t[e+1])==0)
{
return 1;
}
}
return 0;
}
void toword(char *t,int l,int r)
{
int i=0,p=0;
for(i=l; i<=r; i++)
{
Word1[count].word[p++]=t[i];
}
Word1[count].word[p]='\0';
Word1[count].len=r-l+1;
Word1[count].b=l;
Word1[count].e=r;
}
void tofile(char t[])
{
FILE* fp2;
fp2=fopen("myf2.out","a");
if(fp2==NULL)
{
printf("文件打开失败!\n");
return;
}
else
{
fputs(t,fp2);
}
}
void moveword(char t[],int len)
{
int max=Word1[0].len,pos=0;
for(int i=1; i<count; i++)
{
if( Word1[i].len>max)
{
max=Word1[i].len;
pos=i;
}
}
char newsec[150];
int p=0;
for(int i=0; i<len; i++)
{
if(i<Word1[pos].b||i>Word1[pos].e+1)
{
newsec[p++]=t[i];
}
}
for(int i=Word1[pos].b; i<=Word1[pos].e; i++)
{
newsec[p++]=t[i];
}
newsec[p]='\0';
puts(newsec);
tofile(newsec);
}
void FindWord(char *a)
{
int Left=0,Right=0;//左指针Left,右指针Right
int p;
for(Left=0; Left<len; Left++)
{
for(Right=0; Right<len-Left; Right++)
{
if(isw(a,Left,Left+Right)==1)//判断从左指针到右指针,之间是不是一个单词
{
toword(a,Left,Left+Right);
count ++;
break;
}
}
}
moveword(a,len);
}
int main()
{
char t[150];
gets(t);
len=strlen(t);
FindWord(t);
return 0;
}
#include<stdio.h>
#include <conio.h>
#include<ctype.h>
#include<string.h>
void FindWord(char *a,char *b)
{
int i,j;
char c[80];
b[0] = '\0';
j = 0;
if(isalpha(a[0]))
{
c[0]=a[0];
j=1;
}
for(i = 1;i <= strlen(a); i++)
{
if(isalpha(a[i])&&!isalpha(a[i-1]))
{
c[j++]=a[i];
}
else if(isalpha(a[i])&&isalpha(a[i-1]))
{
c[j++]=a[i];
}
else if(!isalpha(a[i])&&isalpha(a[i-1]))
{
c[j++]='\0';
if(strlen(c)>strlen(b))
{
strcpy(b,c);
}
j = 0;
}
}
}
int main()
{ char a[80],b[80];
gets(a);
FindWord(a,b);
printf("%s",b);
return 0;
}