将字符串中单词经排序后输出

思路

先将字符串中的单词分割保存至二维数组中,再经排序后输出。水题,直接上代码了。

代码

/*************************************************************************
    > File Name: words_sort.c
    > Author: KrisChou
    > Mail:zhoujx0219@163.com 
    > Created Time: Sun 24 Aug 2014 08:41:42 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 128
#define WORD_CNT 128
#define WORD_LEN 256

static int my_isspace(char c)
{
    if(c == ' '|| c == '\n' || c == '\t' || c == '\v')
        return 1;
    else
        return 0;
}

static void word_show(char(*words)[WORD_LEN],int cnt)
{
    int index;
    for(index = 0; index < cnt; index++)
    {
        printf("%-15s", words[index]);
    }
}

static void word_save(char *line, int bg, int end, char *dest)
{
    int index,index_dest;
    for(index = bg,index_dest = 0; index <= end; index++,index_dest++)
    {
        dest[index_dest] = line[index];
    }
    dest[index_dest] = '\0';
}

static int word_split(char *line, char(*words)[WORD_LEN])
{
    int bg,end;
    int word_cnt;
    bg = 0;
    word_cnt = 0;
    while(line[bg] != '\0')
    {
        while(my_isspace(line[bg]))
        {
            bg++;
        }
        if(line[bg] == '\0')
        {
            break;
        }
        end = bg;
        while(line[end] != '\0' && !my_isspace(line[end]))
        {
            end++;
        }
        word_save(line,bg,end-1,words[word_cnt++]);
        bg = end;
    }
    return word_cnt;
}

static void word_sort(char(*words)[WORD_LEN],int cnt)
{
    int pos,index;
    char key[WORD_LEN];
    memset(key,0,WORD_LEN);
    for(pos = 1; pos < cnt; pos++)
    {
        strcpy(key,words[pos]);
        for(index = pos - 1; index >= 0; index--)
        {
            if(strcmp(key,words[index]) < 0)
            {
                strcpy(words[index+1],words[index]);
            }else
            {
                break;
            }
        }
        strcpy(words[index+1],key);
    }
}

int main(int argc, char *argv[])
{
    char line[N];
    char arr[WORD_CNT][WORD_LEN];
    int word_cnt;
    while(fflush(stdin),gets(line) != NULL)
    {
        word_cnt = word_split(line,arr);
        word_show(arr,word_cnt);
        printf("\n");
        word_sort(arr,word_cnt);
        word_show(arr,word_cnt);
        printf("\n");

    }
    return 0;
}

转载于:https://www.cnblogs.com/jianxinzhou/p/3933590.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值