用c语言回答,不使用strcat函数,实现两个字符串的连接
时间: 2024-05-05 11:18:48 浏览: 18
可以使用指针实现字符串连接,代码如下:
```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!
```
相关问题
C语言不用指针不用strcat函数实现两个字符串的连接。
在 C 语言中,可以使用数组来操作字符串,从而实现字符串的连接。以下是一种实现方法:
```c
#include <stdio.h>
void string_concat(char dest[], char src[]) {
int i, j;
i = j = 0;
// 指针移动到 dest 的末尾
while (dest[i] != '\0') {
i++;
}
// 将 src 复制到 dest 的末尾
while (src[j] != '\0') {
dest[i] = src[j];
i++;
j++;
}
// 添加字符串结束标志
dest[i] = '\0';
}
int main() {
char str1[100] = "hello";
char str2[50] = "world";
// 连接两个字符串
string_concat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
以上代码中,`string_concat()` 函数接受两个字符串数组 `dest` 和 `src`,然后将 `src` 中的字符复制到 `dest` 的末尾,并在末尾添加字符串结束标志 '\0',从而实现字符串的连接。最后在 `main()` 函数中,调用 `string_concat()` 函数来连接两个字符串,并输出连接后的字符串。
在c语言中怎样实现不用strcat函数连接两个字符串
可以使用循环遍历两个字符串并逐个字符赋值给新的字符串来实现字符串连接,示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "hello";
char str2[50] = "world";
int i, j;
// 计算str1和str2的长度
int len1 = strlen(str1);
int len2 = strlen(str2);
// 新建一个字符串数组,长度为两个字符串长度之和
char str3[len1 + len2 + 1];
// 循环遍历str1和str2并逐个字符赋值给str3
for (i = 0; i < len1; i++) {
str3[i] = str1[i];
}
for (j = 0; j < len2; j++) {
str3[i+j] = str2[j];
}
// 在新字符串末尾添加字符串结束符
str3[i+j] = '\0';
printf("%s\n", str3);
return 0;
}
```
运行结果为:
```
helloworld
```