编写程序,不使用strcat函数实现两个字符串连接,连接字符串“Hello"和”World!"用c语言,不可以用指针
时间: 2024-02-24 14:55:55 浏览: 26
可以使用数组和循环来实现两个字符串的连接,具体代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World!";
int len1 = strlen(str1);
int len2 = strlen(str2);
char result[len1 + len2 + 1]; // 定义结果字符串数组
int i, j;
for (i = 0; i < len1; i++) {
result[i] = str1[i]; // 将第一个字符串添加到结果字符串中
}
for (j = 0; j < len2; j++) {
result[i + j] = str2[j]; // 将第二个字符串添加到结果字符串中
}
result[i + j] = '\0'; // 添加字符串结束标志
printf("%s\n", result); // 输出结果字符串
return 0;
}
```
通过数组和循环,我们可以将两个字符串连接起来并输出结果字符串。
相关问题
编写程序,不使用strcat函数实现两个字符串连接,连接字符串“Hello"和”World!"用c语言
可以使用指针和循环来实现两个字符串的连接,具体代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World!";
int len1 = strlen(str1);
int len2 = strlen(str2);
char* result = (char*)malloc(len1 + len2 + 1); // 申请内存
char* p = result; // 指针指向字符串开头
int i;
for (i = 0; i < len1; i++) {
*p++ = str1[i]; // 将第一个字符串添加到结果字符串中
}
for (i = 0; i < len2; i++) {
*p++ = str2[i]; // 将第二个字符串添加到结果字符串中
}
*p = '\0'; // 添加字符串结束标志
printf("%s\n", result); // 输出结果字符串
free(result); // 释放内存
return 0;
}
```
通过指针和循环,我们可以将两个字符串连接起来并输出结果字符串。
用c语言回答,不使用strcat函数,实现两个字符串的连接
可以使用指针实现字符串连接,代码如下:
```c
#include <stdio.h>
void my_strcat(char *s1, char *s2){
while(*s1 != '\0'){
s1++;
}
while(*s2 != '\0'){
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main(){
char s1[20] = "Hello, ";
char s2[20] = "world!";
my_strcat(s1, s2);
printf("%s\n", s1);
return 0;
}
```
运行结果为:
```
Hello, world!
```