3.编写程序将2个字符串连接起来(不使用strcat函数)并输出。
时间: 2023-05-02 17:03:44 浏览: 60
代码如下:
```
#include <stdio.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World";
char str3[11];
int i, j;
for(i=0; str1[i]!='\0'; i++) {
str3[i] = str1[i];
}
for(j=0; str2[j]!='\0'; j++) {
str3[i+j] = str2[j];
}
str3[i+j] = '\0';
printf("拼接后的字符串为:%s", str3);
return 0;
}
```
相关问题
编写程序将2个字符串连接起来(不使用strcat函数)并输出。
可以使用循环遍历两个字符串,将第一个字符串的每个字符依次存入新的字符串中,再将第二个字符串的每个字符依次存入新的字符串中,最后输出新的字符串即可。
示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], newStr[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串存入新的字符串中
for (i = ; str1[i] != '\'; i++) {
newStr[i] = str1[i];
}
// 将第二个字符串存入新的字符串中
for (j = ; str2[j] != '\'; j++) {
newStr[i + j] = str2[j];
}
// 添加字符串结束符
newStr[i + j] = '\';
printf("连接后的字符串为:%s\n", newStr);
return ;
}
```
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';
}
```
相关推荐
![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)