用C语言把两个字符串连接,中间用逗号隔开
时间: 2024-05-13 21:19:24 浏览: 8
您可以使用C语言的字符串函数 strcat() 和 sprintf() 来实现这个任务。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello";
char str2[100] = "world";
char result[200]; // 用于存储连接后的字符串
strcat(result, str1); // 将 str1 连接到 result 后面
strcat(result, ","); // 添加逗号
strcat(result, str2); // 将 str2 连接到 result 后面
printf("%s\n", result); // 输出连接后的字符串
return 0;
}
```
这个程序会输出 "Hello,world",即两个字符串连接后中间用逗号隔开的结果。
相关问题
C语言把字符串连接,中间用逗号隔开
在C语言中,可以使用strcat()函数将两个字符串连接起来,然后在连接的字符串中间添加逗号。以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char str3[100];
strcpy(str3, str1);
strcat(str3, ",");
strcat(str3, str2);
printf("%s", str3);
return 0;
}
```
输出结果为:Hello,World
是用逗号隔开,输入3次
非常抱歉,我理解有误。以下是使用C语言实现的代码,将从input.txt文件中读取的字符串用逗号隔开输出到output.txt文件中,并显示其中字符数:
```c
#include <stdio.h>
#include <string.h>
int main() {
FILE *input_file, *output_file;
char string[100];
input_file = fopen("input.txt", "r");
fgets(string, 100, input_file); // 从input.txt中读取字符串
fclose(input_file);
int length = strlen(string);
string[length - 1] = '\0'; // 将读取的字符串结尾的换行符改为字符串结束符
output_file = fopen("output.txt", "w");
for(int i=0; i<3; i++){
fputs(string, output_file); // 将字符串写入output.txt
if(i<2){
fputc(',', output_file); // 在字符串后面添加逗号
}
}
fclose(output_file);
printf("字符串长度:%d\n", strlen(string) * 3 + 2); // 输出字符串长度
return 0;
}
```
这段代码首先定义了两个指向文件的指针变量`input_file`和`output_file`,以及一个字符数组`string`用于存储从input.txt中读取的字符串。然后使用`fopen()`函数打开input.txt文件,并使用`fgets()`函数将第一行字符串读取到`string`数组中,最后关闭文件。
接着,在读取的字符串结尾处将换行符`\n`修改为字符串结束符`\0`。然后使用`fopen()`函数打开output.txt文件,并使用`fputs()`函数将字符串写入文件中。在每两个字符串之间添加一个逗号,最后关闭文件。
最后计算输出到文件中的字符串长度(包括逗号),并使用`printf()`函数输出该长度。
注意,使用`fgets()`函数读取字符串时,需要指定读取的最大字符数,以避免内存溢出。在本例中,我指定了100作为最大字符数。如果读取的字符串超过了100个字符,就需要增加数组的大小。