合并字符串的C语言代码
时间: 2024-01-01 18:03:13 浏览: 34
你好!以下是合并字符串的C语言代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100];
printf("请输入第一个字符串:");
gets(str1);
printf("请输入第二个字符串:");
gets(str2);
strcat(str1, str2);
printf("拼接后的字符串是:%s\n", str1);
return 0;
}
```
如果你想了解更多关于C语言的知识,请告诉我。
相关问题
任意个合并字符串的C语言代码
以下是一个任意个合并字符串的C语言代码示例:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = " world!";
char str3[50] = " I'm a chatbot.";
char result[150];
strcpy(result, str1);
strcat(result, str2);
strcat(result, str3);
printf("Merged string : %s\n", result);
return 0;
}
```
输出结果为:
```
Merged string : Hello world! I'm a chatbot.
```
贪心法 合并字符串的C语言代码
以下是合并字符串的C语言代码(使用贪心法):
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n;
scanf("%d", &n);
char** strs = (char**) malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
strs[i] = (char*) malloc(100 * sizeof(char));
scanf("%s", strs[i]);
}
char* res = (char*) malloc(100 * n * sizeof(char));
int len = 0;
while (true) {
int max = -1;
int idx = -1;
for (int i = 0; i < n; i++) {
if (strs[i] == NULL) {
continue;
}
int l = strlen(strs[i]);
if (l > max) {
max = l;
idx = i;
}
}
if (idx == -1) {
break;
}
strcat(res + len, strs[idx]);
len += strlen(strs[idx]);
strs[idx] = NULL;
}
printf("%s\n", res);
for (int i = 0; i < n; i++) {
free(strs[i]);
}
free(strs);
free(res);
return 0;
}
```
希望能够满足您的需求,如果您还有其他问题,也欢迎随时向我提问哦!😊