美文网首页
11.6 字符串示例:字符串排序

11.6 字符串示例:字符串排序

作者: 日常表白结衣 | 来源:发表于2017-07-20 19:41 被阅读0次

字符串排序只要是用strcmp()函数来确定两个字符串的顺序,一般的做法是读取字符串函数,排序字符串并打印出来。
输入示例

o that i was where i would be,
then would i be where i am not,
but where i am i must be,
and where i would be i can not.

输出示例

and where i would be i can not.
but where i am i must be,
o that i was where i would be,
then would i be where i am not,

程序示例

#include<stdio.h>
#include<string.h>
#define SIZE 81
#define LIM 20       /*可读入的最多行数*/
#define HALT ""     /*空格字符串停止输入*/

void stsrt(char *strings[], int num);
char *s_gets(char *st, int n);

int main()
{
    char input[LIM][SIZE]; /*存储输入的数组*/
    char *ptstr[LIM];      /*内含指针变量的数组,均指向每一行的首地址*/
    int ct = 0;            /*输入计数*/
    int k;                 /*输出计数*/

    printf("input up to %d lines,and i will sort them.\n", LIM);
    printf("to stop,press the enter key at a line's start.\n");
/*此处只需要直接指向字符数组某一行的首地址,便可以实现怼字符串的输入*/
    while (ct < LIM&&s_gets(input[ct], SIZE) != NULL&&input[ct][0] != '\0')
    {
        ptstr[ct] = input[ct]; /*设置指针指向字符串*/
        ct++;
    }
    stsrt(ptstr, ct);
    puts("\nhere's the sorted list:\n");
    for (k = 0; k < ct; k++)
        puts(ptstr[k]);       /*排序后的指针*/

    return 0;
}
/*选择排序*/
/*字符串-指针-排序函数&&指针与一维数组*/
void stsrt(char *strings[], int num)
{
    char *temp;
    int top, seek;

    for(top=0;top<num-1;top++)
        for(seek=top+1;seek<num;seek++)
            if (strcmp(strings[top], strings[seek]) > 0)
            {
                temp = strings[top];
                strings[top] = strings[seek];
                strings[seek] = temp;
            }
}
char *s_gets(char *st, int n) /*指针与一维数组*/
{
    char *ret_val;
    int i = 0;

    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        while (st[i] != '\n'&&st[i] != '0')
            i++;
        if (st[i] == '\n')  st[i] = '\0';
        else
            while (getchar() != '\n')
                continue;
    }
    return ret_val;
}

关于strcmp()函数:
strcmp()函数比较所有的字符,不只是字母,如果 第一个字符串位于第二个字符串的前面,strcmp()就返回正数,反之则返回负数。

相关文章

  • 11.6 字符串示例:字符串排序

    字符串排序只要是用strcmp()函数来确定两个字符串的顺序,一般的做法是读取字符串函数,排序字符串并打印出来。输...

  • Redis常用命令

    字符串 设置字符串键值对 规则 示例 批量设置字符串键值对 规则 示例 获取字符串 规则 示例 批量设置字符串 规...

  • js算法

    排序算法 冒泡排序 快速排序 字符串操作 判断回文字符串 翻转字符串 反向遍历字符串 function reve...

  • Android中字符串操作简介

    字符串排序(冒泡排序) 字符串比较大小 反转字符串 获取某段字符 判断字符串中出现的子字符串的次数

  • JS排序

    1、数字排序 2、字符串排序 3、中文排序 4、中英文数字字符串排序

  • LeetCode 451

    根据字符出现频率排序给定一个字符串,请将字符串里的字符按照出现的频率降序排列。 示例 1: 输入:"tree" 输...

  • nodejs实现字符串排序(高位优先&低位优先)

    字符串排序 网上很多都是c实现的,这里我写一个nodejs实现的 低位优先字符串排序 高位优先字符串排序

  • leetCode进阶算法题+解析(五十一)

    根据字符出现频率排序 题目:给定一个字符串,请将字符串里的字符按照出现的频率降序排列。 示例 1:输入:"tree...

  • 面试题48. 最长不含重复字符的子字符串

    题目 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。 示例 1: 示例 2: 示例...

  • 常见算法的js实现

    排序算法 1、冒泡排序 2、快速排序 3、二路归并 字符串操作 1、判断回文字符串 2、翻转字符串 思路一:反向遍...

网友评论

      本文标题:11.6 字符串示例:字符串排序

      本文链接:https://www.haomeiwen.com/subject/zqfjkxtx.html