用c语言做一个代码,连接两个字符串(不用strcat函数)。输入形式:输入两行字符串。输出形式:连接两个字符串。
时间: 2024-05-11 14:15:11 浏览: 74
您好!可以通过以下程序实现连接两个字符串:
```
#include<stdio.h>
#include<string.h>
int main(){
char str1[100], str2[100], res[200];
int i, j, len1, len2;
printf("请输入第一个字符串:");
fgets(str1, sizeof(str1), stdin);
printf("请输入第二个字符串:");
fgets(str2, sizeof(str2), stdin);
len1 = strlen(str1);
len2 = strlen(str2);
for (i = 0; i < len1 - 1; i++) {
res[i] = str1[i];
}
for (j = 0; j < len2; j++) {
res[i + j] = str2[j];
}
res[i + j] = '\0';
printf("连接后的字符串为:%s", res);
return 0;
}
```
这个程序使用 fgets() 函数从标准输入获取两个字符串,然后使用循环将它们连接在一起,最后输出连接后的结果。希望这个程序对您有所帮助!
相关问题
c语言用strcat函数将两个字符串连接起来(输入
在C语言中,`strcat`函数用于将两个字符串连接起来。`strcat`函数的原型如下:
```c
char *strcat(char *dest, const char *src);
```
其中,`dest`是目标字符串,`src`是源字符串。`strcat`函数会将`src`字符串的内容追加到`dest`字符串的末尾,并自动在连接后的字符串末尾添加空字符`\0`。
以下是一个使用`strcat`函数的示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char dest[50] = "Hello, ";
char src[] = "World!";
// 使用strcat连接字符串
strcat(dest, src);
// 输出连接后的字符串
printf("连接后的字符串: %s\n", dest);
return 0;
}
```
在这个示例中,`dest`字符串初始值为"Hello, ",而`src`字符串为"World!"。调用`strcat(dest, src)`后,`src`的内容被追加到`dest`的末尾,最终`dest`的内容变为"Hello, World!"。
用C语言编写程序,实现两字符串的连接,要求程序中不能使用库函数strcat。 【输入形式】 第一行输入一个字符串,以回车结束。 第二行输入一个字符串,以回车结束。 【输出形式】 输出连接后的字符串。 【样例输入】 I am happy 【样例输出】 I am happy
好的,我可以帮你解决这个问题。以下是一个用 C 语言编写的实现两个字符串连接的程序,其中不使用库函数 strcat:
```c
#include <stdio.h>
#include <string.h>
void my_strcat(char* dest, char* src) {
while (*dest) {
dest++;
}
while (*src) {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}
int main() {
char str1[100], str2[100];
fgets(str1, sizeof(str1), stdin);
fgets(str2, sizeof(str2), stdin);
str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';
my_strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
程序首先定义了一个自定义函数 my_strcat,该函数将给定的两个字符串连接在一起,并将结果保存在目标字符串中。该函数首先寻找目标字符串的结尾,然后将源字符串中的所有字符复制到目标字符串的末尾,并在最后添加一个字符串结束符。
主函数中,首先使用 fgets 函数读取两个输入字符串,然后使用 strcspn 函数去掉每个字符串的末尾的换行符。接着调用自定义函数 my_strcat 连接两个字符串,并输出结果。
希望这个程序能够解决你的问题。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.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)