C语言编写一个程序,将将两个字符串连接起来,不能使用 strcat 函数。
时间: 2023-06-04 20:08:05 浏览: 197
可以使用指针来实现字符串的连接,具体的实现过程可以参考如下代码:
```
#include <stdio.h>
void my_strcat(char *str1, char *str2) {
while (*str1) { // 找到 str1 的结尾
str1++;
}
while (*str2) { // 拷贝 str2 中的每个字符到 str1 的结尾
*str1++ = *str2++;
}
*str1 = '\0'; // 在 str1 的结尾加上字符串结束标志
}
int main() {
char str1[100] = "Hello, ";
char str2[] = "world!";
my_strcat(str1, str2);
printf("%s\n", str1); // 输出 "Hello, world!"
return 0;
}
```
以上代码中,我们用两个 while 循环来找到第一个字符串的结尾和拷贝第二个字符串中的每个字符到第一个字符串的结尾。最后,在第一个字符串的结尾处添加字符串结束标志 '\0'。
相关问题
使用C语言编写一个程序,将两个字符串连接起来,不要用strcat函数
好的,以下是使用C语言编写的将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
#include <string.h>
void my_strcat(char *s1, char *s2) {
while (*s1) {
s1++;
}
while (*s2) {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char str1[50], str2[50];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
my_strcat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
在这个程序中,我们定义了一个名为`my_strcat`的函数,它接受两个指向字符数组的指针作为参数,将第二个字符串连接到第一个字符串的末尾。具体实现如下:
- 使用一个while循环找到第一个字符串的末尾。
- 然后使用另一个while循环将第二个字符串的每个字符复制到第一个字符串的末尾。
- 最后将第一个字符串的末尾设置为'\0'。
在主函数中,我们首先从用户那里获取两个字符串,然后调用`my_strcat`函数将它们连接起来,最后输出结果。
需要注意的是,这个程序假设两个字符串都是以'\0'结尾的。如果不是,可能会导致程序崩溃或产生意外结果。所以,实际应用中还需要对输入进行有效性判断。
用c语言编写一个程序,将两个字符串连接起来,不能使用strcat函数。
好的,我可以用以下代码来实现:
```c
#include <stdio.h>
int main()
{
char str1[50], str2[50];
int i, j;
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
for(i = 0; str1[i] != '\0'; i++); // Find the end of the first string
for(j = 0; str2[j] != '\0'; j++, i++)
{
str1[i] = str2[j]; // append the second string to the first
}
str1[i] = '\0'; // Add null character at the end of the concatenated string
printf("The concatenated string is: %s", str1);
return 0;
}
```
这个程序通过遍历两个字符串来实现字符串的拼接。