2.编一个程序,将两个字符串连接起来,不要用strcat函数。
时间: 2023-06-16 20:06:37 浏览: 62
可以使用以下代码实现:
```c
#include <stdio.h>
void string_concat(char* str1, char* str2) {
int i, j;
for (i = 0; str1[i] != '\0'; i++);
for (j = 0; str2[j] != '\0'; j++) {
str1[i + j] = str2[j];
}
str1[i + j] = '\0';
}
int main() {
char str1[100], str2[50];
printf("请输入第一个字符串:");
gets(str1);
printf("请输入第二个字符串:");
gets(str2);
string_concat(str1, str2);
printf("合并后的字符串为:%s", str1);
return 0;
}
```
这里使用了两个for循环,第一个循环找到第一个字符串的末尾位置,第二个循环将第二个字符串中的字符逐个拷贝到第一个字符串的末尾位置,最后在末尾位置添加一个'\0',表示字符串的结束。
相关问题
2.编写一个程序,将两个字符串连接起来,不要用strcat函数
以下是一个不使用strcat函数的程序,将两个字符串连接起来:
```c
#include <stdio.h>
#include <string.h>
void my_strcat(char* s1, char* s2);
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;
}
void my_strcat(char* s1, char* s2) {
int len1 = strlen(s1);
int len2 = strlen(s2);
for (int i = 0; i < len2; i++) {
s1[len1 + i] = s2[i];
}
s1[len1 + len2] = '\0';
}
```
3.编一程序,将两个字符串连接起来,不要用strcat函数。
好的,可以使用以下程序实现:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i, j;
// 读入两个字符串
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 求出第一个字符串的长度
for (i = 0; str1[i] != '\0'; i++);
// 将第二个字符串添加到第一个字符串的结尾处
for (j = 0; str2[j] != '\0'; j++) {
str1[i + j] = str2[j];
}
// 添加字符串结束标志
str1[i + j] = '\0';
// 输出连接后的字符串
printf("连接后的字符串是:%s\n", str1);
return 0;
}
```
这个程序中,我们使用了两个 for 循环来实现字符串的连接。第一个 for 循环求出了第一个字符串的长度,把指针移动到了第一个字符串的结尾处。然后,第二个 for 循环将第二个字符串的字符复制到第一个字符串的结尾处,并添加字符串结束标志。最后,我们输出了连接后的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)