华为机试—字符串中找出单词排序

该博客介绍了一道华为机试题目,要求从给定字符串中找出单词,按照长度降序排序。如果单词长度相同,则按原始顺序排列,并确保重复单词只出现一次。最终将排序后的单词以空格分隔存入新字符串。输入输出字符串的函数原型及要求也在文中说明。
摘要由CSDN通过智能技术生成

题目:

在给定字符串中找出单词( “单词”由大写字母和小写字母字符构成,其他非字母字符视为单词的间隔,如空格、问号、数字等等;另外单个字母不算单词);找到单词后,按照长度进行降序排序,(排序时如果长度相同,则按出现的顺序进行排列),然后输出到一个新的字符串中;如果某个单词重复出现多次,则只输出一次;如果整个输入的字符串中没有找到单词,请输出空串。输出的单词之间使用一个“空格”隔开,最后一个单词后不加空格。

要求实现函数:
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;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值