.输入两个字符串(小于 40 个字符),连接后输出(不得使用系统串连接函数)c语言代码
时间: 2024-05-14 08:19:08 浏览: 11
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[40], str2[40], result[80];
int i, j;
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
// 将第一个字符串复制到结果字符串中
for (i = 0; str1[i] != '\0'; i++) {
result[i] = str1[i];
}
// 将第二个字符串复制到结果字符串中
for (j = 0; str2[j] != '\0'; j++) {
result[i + j] = str2[j];
}
// 添加字符串结束符
result[i + j] = '\0';
printf("Concatenated string: %s\n", result);
return 0;
}
```
相关问题
2. 输入两个字符串(小于 40 个字符),连接后输出(不得使用系统串连接函数).写一个C语言程序
可以使用指针来实现字符串连接,以下是一个简单的C语言程序:
```c
#include <stdio.h>
void str_concat(char *str1, char *str2, char *result) {
int i, j;
for (i = 0; str1[i] != '\0'; i++) {
result[i] = str1[i];
}
for (j = 0; str2[j] != '\0'; j++) {
result[i+j] = str2[j];
}
result[i+j] = '\0';
}
int main() {
char str1[40], str2[40], result[80];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
str_concat(str1, str2, result);
printf("连接后的字符串为:%s\n", result);
return 0;
}
```
程序中的 `str_concat` 函数接收两个字符串和一个结果字符串的指针,使用循环将第一个字符串拷贝到结果字符串中,再将第二个字符串拷贝到结果字符串的末尾,最后在末尾加上字符串结束符 `\0`。在 `main` 函数中,先接收两个输入字符串,再调用 `str_concat` 函数进行字符串连接,最后输出结果字符串。
用c语言编写程序: 输入两个字符串(小于 40 个字符),连接后输出(不得使用系统串连接函数)。
可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[41], str2[41], result[81];
int i, j;
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
// 将第一个字符串复制到结果字符串中
strcpy(result, str1);
// 将第二个字符串连接到结果字符串的末尾
for (i = strlen(str1), j = 0; j < strlen(str2); i++, j++) {
result[i] = str2[j];
}
// 添加字符串结束符
result[i] = '\0';
printf("The concatenated string is: %s\n", result);
return 0;
}
```
该程序首先通过 `scanf()` 函数获取用户输入的两个字符串。然后,使用 `strcpy()` 函数将第一个字符串复制到结果字符串中。最后,使用循环将第二个字符串连接到结果字符串的末尾,并在末尾添加字符串结束符。最终,程序输出连接后的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)