将两个字符串连接起来,不要用 strcat 函数。流程图
时间: 2023-12-15 07:32:15 浏览: 67
以下是将两个字符串连接起来的C语言代码,不使用strcat函数:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
i = strlen(str1);
for (j = 0; str2[j] != '\0'; i++, j++) {
str1[i] = str2[j];
}
str1[i] = '\0';
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
流程图如下:
```
开始
输入第一个字符串
输入第二个字符串
计算第一个字符串长度
将第二个字符串连接到第一个字符串后面
输出连接后的字符串
结束
```
相关问题
c语言将两个字符串连接起来不要用strcat函数
可以使用循环将第二个字符串中的每个字符添加到第一个字符串的末尾,直到第二个字符串的结尾标志'\0'。例如:
```c
#include <stdio.h>
void mystrcat(char *s1, const char *s2) {
while (*s1) { // 找到s1的结尾
s1++;
}
while (*s2) { // 将s2中的字符添加到s1的末尾
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0'; // 添加字符串结尾标志
}
int main() {
char s1[20] = "Hello, ";
char s2[] = "world!";
mystrcat(s1, s2);
printf("%s\n", s1); // 输出Hello, world!
return 0;
}
```
c++将两个字符串连接起来,不要用strcat函数。
以下是两种C++将两个字符串连接起来的方法,不使用strcat函数:
1.使用循环遍历字符串并逐个复制到新的字符串中:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[20], str2[20], result[40];
cin >> str1 >> str2;
int len1 = strlen(str1), len2 = strlen(str2);
for (int i = 0; i < len1; i++) {
result[i] = str1[i];
}
for (int i = 0; i < len2; i++) {
result[len1 + i] = str2[i];
}
result[len1 + len2] = '\0';
cout << result << endl;
return 0;
}
```
2.使用指针遍历字符串并逐个复制到新的字符串中:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[20], str2[20], result[40];
cin >> str1 >> str2;
char *p1 = str1, *p2 = str2, *p3 = result;
while (*p1 != '\0') {
*p3++ = *p1++;
}
while (*p2 != '\0') {
*p3++ = *p2++;
}
*p3 = '\0';
cout << result << endl;
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)