字符串例题:字符串排序
例题
按字母表顺序排序字符串
一般做法是读取字符串,排序字符串并打印出来。
#include<stdio.h>
#include<assert.h>
#include<string.h>
#define ROW 20
#define SIZE 81
void select_Sort(char* str[], int n); //当作字符串排序函数
char* s_gets(char* st, int n); //此函数可读取整行输入用空字符代替换行符
int main(void)
{
char input[ROW][SIZE]; //存储输入的数组
char* ptstr[ROW]; //内含指针变量的数组
int ct = 0; //输入计数
int i = 0; //输出计数
printf("Please input up to %d lines:\n", ROW);
printf("To stop, please press Enter key at a line's start.\n");
while (ct < ROW && s_gets(input[ct], SIZE) != nullptr && input[ct][0] != '\0')
{
ptstr[ct] = input[ct]; //让指针指向字符串
ct++;
}
select_Sort(ptstr, ct); //字符串排序
puts("\nHere's the sorted list:\n");
for (i = 0; i < ct; ++i)
{
puts(ptstr[i]); //排序后输出
}
return 0;
}
void select_Sort(char* str[], int n)
{
char* temp;
int i, j;
for (i = 0; i < n - 1; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (strcmp(str[i], str[j]) > 0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
char* s_gets(char* st, int n)
{
assert(st != nullptr);
char* ret_val = fgets(st, n, stdin);
int i = 0;
if (ret_val)
{
while (st[i] != '\0' && st[i] != '\n')
++i;
if (st[i] == '\n')
st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
运行结果:
先试着拿一些歌词输入进去
确实是由**strcmp()**函数对字符串依次比较并排序的结果。
但要注意的是:
排序的是指针而非字符串
起初,ptstr[0]指向input[0], ptstr[1]指向input[1]以此类推。
排序过程把ptstr重新排列,并未改变input.
比如排序前是这样:
排序后变成
**ptstr[0]指向input[2];
ptstr[1]指向input[1];**等等
选择排序算法介绍
具体做法是利用for循环依次把每个元素与首元素比较。如果待比较的元素在当前首元素的前面,则两者交换。
循环结束时,外层循环重复这一过程,这次从input的第二个元素开始。。。
伪代码:
for n = 首元素至n = 倒数第二个元素,
找出剩余元素中的最大值,并将其放在第n个元素中
通用程序代码:
void select_Sort(char* str[], int n)
{
char* temp;
int i, j;
for (i = 0; i < n - 1; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (strcmp(str[i], str[j]) > 0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
若不是排序字符串,而是要求一个整型数组ar[]排序,代码也差不多一样,只需将if语句的判断条件换成ar[i] > ar[j]即可。。
借助ctype.h的字符函数
toupper()函数
这个函数是将单个字符从小写转换为大写,但若要处理整个字符串,可以对此函数稍微改造一下:
#include<ctype.h>
void ToUpper(char* str)
{
while (*str)
{
*str = toupper(*str);
str++;
}
}
这样可以将传进来的字符串进行小写转大写,很合理。
还有其他一些函数也会用到,比如计算字符串中的标点符号个数。
ispunct()函数
int PunctCount(const char* str)
{
int count = 0;
while (*str)
{
if (ispunct(*str))
count++;
str++;
}
return count;
}
命令行参数简介
命令行是在命令行环境中,用户为运行程序输入命令的行。
当main()有两个参数时,第一个参数是命令行中字符串的数量,这个int类型的参数被称为argc (arguement count);程序把命令行字符串存储在内存中,并把每个字符串的地址存储在指针数组中,该数组地址就是main()的第二个参数,这个指向指针的指针被称为argv (arguement value).
字符串转数字函数简介
atoi(), atol(), atof()函数把字符串形式的数字分别转换成int , long 和double类型的数字。
示例:
#include<stdio.h>
#include<stdlib.h>
int main()
{
const char* s = "123e5";
printf("%d\n", atoi("123"));
printf("%d\n%d\n", atoi("123abc"), atoi("abc"));
return 0;
}
运行结果:
当字符串没有数字时,atoi()返回0。