题目:
在给定字符串中找出单词( “单词”由大写字母和小写字母字符构成,其他非字母字符视为单词的间隔,如空格、问号、数字等等;另外单个字母不算单词);找到单词后,按照长度进行降序排序,(排序时如果长度相同,则按出现的顺序进行排列),然后输出到一个新的字符串中;如果某个单词重复出现多次,则只输出一次;如果整个输入的字符串中没有找到单词,请输出空串。输出的单词之间使用一个“空格”隔开,最后一个单词后不加空格。
要求实现函数:
void my_word(charinput[], char output[])
【输入】 char input[], 输入的字符串
【输出】 char output[],输出的字符串
【返回】 无
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void my_word(char input[],char output[])
{
char *p;
char *temp;
char *word[10];
int len_input=strlen(input);
int i,j;
char except[] = ",";
char *blank = " ";
for (i=0;i<len_input;i++)
{
if (input[i]<'A' || (input[i]>'Z'&&input[i]<'a') || input[i]>'z')
{
input[i]=',';
}
}
j=0;
/*保存取出的单词*/
p= strtok(input,except);
while(NULL!=p)
{
word[j++]=p;
p= strtok(NULL,except);
}
for(i=0;i<j;i++)
printf("%s ",word[i]);
printf("\n");
int wordlen=j;
/*对单词按照长度降序排序,冒泡法*/
for (i=0;i<wordlen;i++)
{
for (j=1;j<wordlen-i;j++)
{
if(strlen(word[j-1])<strlen(word[j]))
{
temp=word[j];
word[j]=word[j-1];
word[j-1]=temp;
}
}
}
/*删除相同单词*/
for (i=0;i<wordlen;i++)
{
for(j=i+1;j<wordlen;j++)
{
if(strcmp(word[i],word[j])==0)
word[j]="\0";
}
}
/*将单词连接起来输出*/
for (j=0;j<wordlen;j++)
{
if (j==0)
strncpy(output,word[j],strlen(word[j])+1);
else
{
strcat(output,blank);
strcat(output,word[j]);
}
}
}
int main()
{
char input[] ="some local buses, some1234123drivers";
printf("筛选之前的字符串:%s\n",input);
char output[30];
my_word(input,output);
printf("筛选之后的字符串:%s",output);
printf("\n");
return 0;
}