c语言编程将两个字符串连接成一个字符串,并将连接后的字符串按升序排列。
时间: 2023-12-26 18:06:04 浏览: 54
可以使用 strcat() 函数将两个字符串连接起来,然后使用 strcmp() 函数进行字符串的比较,最后使用冒泡排序进行升序排列。以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void bubble_sort(char *str[], int n);
int main() {
char str1[MAX_LEN], str2[MAX_LEN], *str[2];
printf("Enter the first string: ");
fgets(str1, MAX_LEN, stdin);
printf("Enter the second string: ");
fgets(str2, MAX_LEN, stdin);
// 去掉换行符
str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';
// 连接字符串
strcat(str1, str2);
// 按升序排列
str[0] = str1;
str[1] = str2;
bubble_sort(str, 2);
printf("The sorted string is: %s\n", str1);
return 0;
}
// 冒泡排序
void bubble_sort(char *str[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
char *tmp = str[j];
str[j] = str[j + 1];
str[j + 1] = tmp;
}
}
}
}
```
注意:在连接字符串之前,需要去掉输入字符串中自带的换行符,否则会影响字符串的比较和排序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)