编写一个类似于strcat()的字符串连接函数,并在主函数中调用,输出连接后的内容。输出如下:连接后的字符串:How are you?Fine,thank you.
时间: 2024-02-28 09:56:31 浏览: 26
好的,以下是一个类似于strcat()的字符串连接函数的实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
char* my_strcat(char* dest, const char* src) {
char* p = dest + strlen(dest);
while (*src != '\0') {
*p++ = *src++;
}
*p = '\0';
return dest;
}
int main() {
char s1[] = "How are you?";
char s2[] = "Fine,thank you.";
my_strcat(s1, s2);
cout << "连接后的字符串:" << s1 << endl;
return 0;
}
```
输出结果:
```
连接后的字符串:How are you?Fine,thank you.
```
该函数的基本思路是找到dest字符串的末尾,然后将src字符串中的字符逐个追加到dest字符串中。最后在dest字符串的末尾添加一个空字符('\0'),表示字符串的结束。
相关问题
C语言编写一个类似于strcat()的字符串连接函数,并在主函数中调用
好的,下面是一个类似于`strcat()`的字符串连接函数的C语言代码:
```c
#include <stdio.h>
#include <string.h>
void mystrcat(char *s1, const char *s2) {
while (*s1) {
s1++;
}
while (*s2) {
*s1++ = *s2++;
}
*s1 = '\0';
}
int main() {
char str1[20] = "Hello, ";
const char *str2 = "world!";
mystrcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
这个函数的功能与`strcat()`类似,都是将两个字符串连接起来,但是它是自己实现的,不使用库函数。它的参数是一个指向目标字符串的指针`s1`和一个指向源字符串的指针`s2`,它会将`s2`中的字符逐个复制到`s1`的末尾,直到遇到`\0`为止。注意,`s1`必须有足够的空间来容纳`s2`,否则会导致缓冲区溢出。在上面的示例中,我们先声明了一个长度为20的字符数组`str1`,然后将它初始化为`"Hello, "`,再定义一个指向`"world!"`的常量字符串`str2`,最后调用`mystrcat()`函数将两个字符串连接起来,输出结果为`"Hello, world!"`。
c语言编写一个类似于strcat()的字符串连接函数
可以按照下面的代码实现一个类似于strcat()的字符串连接函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *str_concat(char *dest, const char *src)
{
int len_dest = strlen(dest);
int len_src = strlen(src);
char *result = (char *) malloc(len_dest + len_src + 1);
if (result == NULL) {
return NULL;
}
strcpy(result, dest);
strcpy(result + len_dest, src);
return result;
}
int main()
{
char str1[20] = "hello ";
char str2[] = "world!";
char *result = str_concat(str1, str2);
if (result == NULL) {
printf("Error: memory allocation failed.\n");
return 1;
}
printf("The concatenated string is: %s\n", result);
free(result);
return 0;
}
```
在这个函数中,我们首先计算了目标字符串和源字符串的长度,然后使用malloc()函数动态分配足够的内存空间来存储连接后的字符串。接着,我们将目标字符串和源字符串依次复制到新分配的内存空间中,最后返回连接后的字符串的指针。在主函数中,我们调用str_concat()函数连接两个字符串,并在连接成功后打印出连接后的字符串,最后释放分配的内存空间。