有5个字符串,首先将它们按照字符串中的字符个数由小到大排列,再分别取出每个字符串的第三个字母合并成一个新的字符串输出(若少于三个字符的输出空格)。要求:利用字符串指针和指针数组实现。
时间: 2023-06-19 17:05:04 浏览: 116
下面是一份可能的实现,其中用到了字符串指针、指针数组和qsort函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_LEN 100
int cmp(const void *a, const void *b) {
return strlen(*(char **)a) - strlen(*(char **)b);
}
int main() {
char str[5][STR_LEN] = {"abcd", "efg", "hijkl", "mn", "opqrs"};
char *p[5];
int i;
for (i = 0; i < 5; i++) {
p[i] = str[i];
}
qsort(p, 5, sizeof(char *), cmp);
char res[STR_LEN] = {0};
for (i = 0; i < 5; i++) {
if (strlen(p[i]) >= 3) {
res[i] = p[i][2];
} else {
res[i] = ' ';
}
}
printf("New string: %s\n", res);
return 0;
}
```
首先定义了一个字符串数组和一个指针数组,然后将指针数组中每个元素都指向字符串数组中对应的字符串。
接着定义了一个比较函数cmp,用于在排序时按字符串长度从小到大排列。这里用到了qsort函数,它可以快速地对一个数组进行排序。
在主函数中,将指针数组p传给qsort函数进行排序。然后遍历排好序的指针数组,根据题目要求取出每个字符串的第三个字母或者输出空格,将它们合并成一个新的字符串res。
最后输出新字符串res即可。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![tcl](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)