11.6 字符串示例:字符串排序
来源:互联网 发布:tomcat80端口被占用 编辑:程序博客网 时间:2024/05/16 09:29
字符串排序只要是用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()就返回正数,反之则返回负数。
阅读全文
0 0
- 11.6 字符串示例:字符串排序
- 字符串排序示例
- 字符串示例
- 字符串:字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序。
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 字符串排序
- 理解MySQL——索引与优化
- 七牛上传图片第一次成功后面不成功
- 初学acmer--读《算法竞赛入门经典》笔记(三)p27-34
- How to fix the problem of executing gitenv.csh file failed
- JavaWeb使用Struts2的简单案例
- 11.6 字符串示例:字符串排序
- 11.5 字符串:选择排序
- 14.1 结构和其他数据形式:结构体
- 14.2 结构和其他数据形式:嵌套结构
- 14.5 结构和其他数据形式:指针和结构
- 微信小程序(5)-新闻页面制作(1)
- 14.5 结构和其他数据形式:传递结构
- Objective-C NSValue详解
- Android6.0运行时权限