用C语言编写程序,将两个字符串连接起来,不要用strcat函数
时间: 2023-11-22 21:52:02 浏览: 212
可以用指针来实现字符串连接。
以下是一个简单的例子:
```c
#include <stdio.h>
void mystrcat(char *dest, const char *src) {
// 将 dest 指针移动到字符串末尾
while (*dest != '\0') {
dest++;
}
// 将 src 复制到 dest 的末尾
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
// 将字符串结束符添加到 dest 的末尾
*dest = '\0';
}
int main() {
char str1[100] = "Hello, ";
char str2[] = "world!";
mystrcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
输出:
```
Hello, world!
```
在上面的代码中,`mystrcat` 函数将 `src` 指向的字符串追加到 `dest` 指向的字符串的末尾。首先,它将 `dest` 指针移动到字符串末尾,然后将 `src` 复制到 `dest` 的末尾,最后添加字符串结束符到 `dest` 的末尾。
相关问题
编写一个程序,将两个字符串连接起来,不要用strcat函数。用C语言代码编写
好的,以下是用C语言代码编写一个将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
void my_strcat(char *str1, char *str2){
while(*str1){
str1++;
}
while(*str2){
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}
int main()
{
char str1[50] = "Hello";
char str2[50] = " world!";
my_strcat(str1, str2);
printf("%s", str1);
return 0;
}
```
这个程序通过指针来实现字符串的连接。首先找到第一个字符串的结尾,然后遍历第二个字符串的每一个字符,并将其逐一拼接到第一个字符串的结尾,最后加上一个终止符。运行该程序将输出"Hello world!"。
编写一个程序,将两个字符串连接起来,不要用strcat函数,c语言
下的程序该如何编写?
可以使用以下代码实现字符串连接功能:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str1[20] = "Hello";
char str2[20] = " World!";
int i, j;
for (i = 0; str1[i] != '\0'; ++i);
for (j = 0; str2[j] != '\0'; ++j, ++i)
{
str1[i] = str2[j];
}
str1[i] = '\0';
printf("Concatenated string: %s", str1);
return 0;
}
```
这段程序先定义了两个字符串 str1 和 str2,然后使用 for 循环找到字符串 str1 的末尾,将字符串 str2 中的字符一一赋值给字符串 str1,最后在字符串 str1 的末尾添加一个空字符 '\0',表示字符串的结束。
需要注意的是,在实际的开发中,应该对要连接的字符串进行长度和内存空间的判断和管理,以避免出现 overflow 或 memory leak 的问题。
阅读全文
相关推荐













