用c语言编写一个程序,将两个字符串连接,并输出连接后的结果。(要求:将第二个字符串连入第一个字符串,不要用strcat函数)
时间: 2024-05-05 10:18:43 浏览: 5
好的,下面是C语言代码示例:
```
#include<stdio.h>
#include<string.h>
int main() {
char str1[100], str2[50];
int i, j;
printf("请输入第一个字符串: ");
scanf("%s", str1);
printf("请输入第二个字符串: ");
scanf("%s", str2);
// 连接两个字符串
for(i = 0; str1[i] != '\0'; i++);
for(j = 0; str2[j] != '\0'; j++, i++) {
str1[i] = str2[j];
}
str1[i] = '\0';
printf("连接后的字符串为: %s\n", str1);
return 0;
}
```
希望能够帮到你,还有需要我回答的问题吗?
相关问题
使用C语言编写一个程序,将两个字符串连接起来,不要用strcat函数
好的,以下是使用C语言编写的将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
#include <string.h>
void my_strcat(char *s1, char *s2) {
while (*s1) {
s1++;
}
while (*s2) {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char str1[50], str2[50];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
my_strcat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
在这个程序中,我们定义了一个名为`my_strcat`的函数,它接受两个指向字符数组的指针作为参数,将第二个字符串连接到第一个字符串的末尾。具体实现如下:
- 使用一个while循环找到第一个字符串的末尾。
- 然后使用另一个while循环将第二个字符串的每个字符复制到第一个字符串的末尾。
- 最后将第一个字符串的末尾设置为'\0'。
在主函数中,我们首先从用户那里获取两个字符串,然后调用`my_strcat`函数将它们连接起来,最后输出结果。
需要注意的是,这个程序假设两个字符串都是以'\0'结尾的。如果不是,可能会导致程序崩溃或产生意外结果。所以,实际应用中还需要对输入进行有效性判断。
用c语言 编写程序,不使用strcat将两个字符串连接起来组成新的字符串输出
您可以使用循环来将两个字符串连接起来,然后输出结果。以下是一个例子:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100], result[200];
int i, j;
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
// 将第一个字符串复制到结果字符串中
for (i = 0; str1[i] != '\0'; i++) {
result[i] = str1[i];
}
// 将第二个字符串连接到结果字符串后面
for (j = 0; str2[j] != '\0'; j++) {
result[i + j] = str2[j];
}
// 在结果字符串的末尾添加结束符
result[i + j] = '\0';
printf("The concatenated string is: %s", result);
return 0;
}
```
在上面的例子中,我们首先定义了三个字符数组,分别存储第一个字符串、第二个字符串和结果字符串。然后,我们使用两个循环将两个字符串连接起来,最后输出结果字符串。需要注意的是,在结果字符串的末尾添加了一个结束符,以确保字符串的正确性。