c语言编写程序将两个字符串连接,不要用stract函数。
时间: 2024-05-09 15:18:34 浏览: 14
可以使用循环遍历字符串,将第一个字符串的每个字符依次复制到新字符串中,再将第二个字符串的每个字符也依次复制到新字符串末尾即可实现字符串连接。具体的实现可以参考以下代码:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str1[100], str2[100], new_str[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串的字符复制到新字符串中
for (i = 0; str1[i] != '\0'; i++) {
new_str[i] = str1[i];
}
// 将第二个字符串的字符复制到新字符串末尾
for (j = 0; str2[j] != '\0'; j++) {
new_str[i + j] = str2[j];
}
// 添加字符串结束标志
new_str[i + j] = '\0';
printf("连接后的字符串为:%s\n", new_str);
return 0;
}
```
相关问题
用c语言将两个字符串连接,不要用stract函数。
可以用循环来实现字符串连接,具体步骤如下:
1.先找到第一个字符串的结尾位置。
2.从第一个字符串的结尾位置开始,依次将第二个字符串中的字符赋值给第一个字符串对应的位置。
3.在第一个字符串的结尾位置添加字符串结束符号'\0'。
下面是示例代码:
```c
#include <stdio.h>
int main() {
char str1[100] = "hello";
char str2[50] = ", world!";
int i, j;
// 找到 str1 的结尾位置
i = 0;
while (str1[i] != '\0') {
i++;
}
// 将 str2 中的字符依次赋值给 str1
j = 0;
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
// 添加字符串结束符号
str1[i] = '\0';
printf("Result: %s\n", str1);
return 0;
}
```
输出结果为:Result: hello, world!
将两个字符串连接,不用stract函数 C语言
可以使用字符数组和指针来实现字符串的连接,具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[20] = "hello";
char str2[20] = "world";
char *result;
result = (char *)malloc(strlen(str1) + strlen(str2) + 1); // 申请空间
if (result == NULL) // 判断是否申请成功
{
printf("Memory allocation failed.\n");
exit(1);
}
strcpy(result, str1); // 拷贝第一个字符串
strcat(result, str2); // 连接第二个字符串
printf("The result of string concatenation is: %s\n", result);
free(result); // 释放内存
return 0;
}
```
输出结果为:
```
The result of string concatenation is: helloworld
```