编一程序,将两个字符串连接起来,不要用strcat函数
时间: 2023-12-15 20:59:30 浏览: 46
好的,下面是将两个字符串 s1 和 s2 进行连接的程序,不使用 strcat 函数:
```c
#include <stdio.h>
void my_strcat(char s1[], char s2[]) {
int i = 0, j = 0;
// 将 i 移动至 s1 的结束位置
while (s1[i] != '\0') {
i++;
}
// 将 s2 中的字符逐个复制到 s1 的结尾
while (s2[j] != '\0') {
s1[i] = s2[j];
i++;
j++;
}
// 加上字符串结束符
s1[i] = '\0';
}
int main() {
char s1[100], s2[100];
printf("请输入字符串s1:");
gets(s1);
printf("请输入字符串s2:");
gets(s2);
// 调用自定义的字符串连接函数
my_strcat(s1, s2);
printf("连接后的字符串为:%s\n", s1);
return 0;
}
```
以上程序执行后会要求用户输入两个字符串,然后将它们连接起来并输出。
相关问题
编一程序,将两个字符串连接起来,用strcat函数;
好的,这个问题很简单。下面是一个使用 strcat 函数的示例程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World!";
strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
这个程序会将 "Hello" 和 "World!" 两个字符串连接起来,并输出结果 "HelloWorld!"。
编一程序,将两个字符串连接起来,不要用strcat函数
### 回答1:
可以使用循环遍历第一个字符串,将每个字符依次存入新的字符串中,然后再遍历第二个字符串,将每个字符依次存入新的字符串中,最终得到两个字符串连接起来的结果。
示例代码:
```
#include <stdio.h>
int main() {
char str1[100], str2[100], new_str[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串存入新的字符串中
for (i = 0; str1[i] != '\0'; i++) {
new_str[i] = str1[i];
}
// 将第二个字符串存入新的字符串中
for (j = 0; str2[j] != '\0'; j++) {
new_str[i+j] = str2[j];
}
// 添加字符串结束符
new_str[i+j] = '\0';
printf("连接后的字符串为:%s\n", new_str);
return 0;
}
```
### 回答2:
在C语言中,可以用指针和循环来实现将两个字符串连接起来的功能。
具体步骤如下:
1. 定义两个字符串s1和s2,并将它们赋值。
2. 定义目标字符串s3,长度为s1和s2字符串长度之和加1。
3. 定义指针p1和p2,分别指向字符串s1和s2的第一个字符。
4. 定义指针p3,指向字符串s3的第一个字符。
5. 使用循环将s1中的字符依次赋值给s3。
6. 使用另一个循环将s2中的字符依次赋值给s3,同时将指针p3向后移动。
7. 最后将s3的末尾置为“\0”,表示字符串的结束。
下面是示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Hello";
char s2[] = "world";
int len1 = strlen(s1);
int len2 = strlen(s2);
char s3[len1 + len2 + 1];
char *p1 = s1;
char *p2 = s2;
char *p3 = s3;
int i;
for (i = 0; i < len1; i++) {
*p3++ = *p1++;
}
for (i = 0; i < len2; i++) {
*p3++ = *p2++;
}
*p3 = '\0';
printf("%s\n", s3);
return 0;
}
```
运行此程序将输出:“Helloworld”,即s1和s2字符串已经成功连接起来。
以上就是用C语言实现将两个字符串连接起来的方法,虽然没有使用strcat函数,但同样可以达到相同的效果。
### 回答3:
字符串连接是我们在日常编程中非常常见的一个操作。通常,我们可以使用strcat函数将两个字符串连接起来。但是,如果要求不使用strcat函数,我们该如何实现呢?
一种常见的做法是:使用循环遍历两个字符串,将第一个字符串的每个字符依次拼接到第二个字符串的末尾,最终得到一个新的字符串。具体实现如下:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str1[20], str2[20], newStr[40];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 拼接字符串
for(i=0; str1[i]!='\0'; i++)
{
newStr[i] = str1[i];
}
for(j=0; str2[j]!='\0'; j++)
{
newStr[i+j] = str2[j];
}
newStr[i+j] = '\0';
printf("拼接后的字符串为:%s\n", newStr);
return 0;
}
```
在此程序中,我们首先定义了三个字符串变量:str1、str2和newStr。然后,我们通过从键盘读入的方式分别获取了两个字符串。
接着,我们使用了两个循环遍历了这两个字符串。第一个循环将第一个字符串的每个字符都拼接到了newStr字符串中。第二个循环将第二个字符串的每个字符也都拼接到了newStr字符串的末尾。
最后,我们在newStr字符串的结尾添加了一个'\0'字符,表示字符串的结束。然后,我们将拼接后的字符串打印输出。
需要注意的是,在拼接字符串之前,我们需要先确定newStr字符串的空间大小,防止出现内存溢出的情况。
总之,通过上述方式,我们就可以轻松地实现字符串的拼接。当然,如果需要频繁地进行字符串拼接操作,我们建议可以自己封装一个字符串拼接函数,以方便代码的重用。