编一个程序,将两个字符串连接起来,不要用strcat函数。
时间: 2023-04-26 18:00:58 浏览: 60
可以使用循环遍历两个字符串,将第一个字符串的每个字符依次赋值给新的字符串,再将第二个字符串的每个字符依次赋值给新的字符串,最后在新的字符串的末尾添加一个空字符'\',表示字符串的结束。
示例代码如下:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100], new_str[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串的字符依次赋值给新的字符串
for (i = ; str1[i] != '\'; i++) {
new_str[i] = str1[i];
}
// 将第二个字符串的字符依次赋值给新的字符串
for (j = ; str2[j] != '\'; j++) {
new_str[i + j] = str2[j];
}
// 在新的字符串的末尾添加一个空字符'\'
new_str[i + j] = '\';
printf("连接后的字符串为:%s\n", new_str);
return ;
}
```
相关问题
编一程序,将两个字符串连接起来,不要用strcat函数
以下是一个简单的程序,用于将两个字符串连接起来,不使用strcat函数:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i, j;
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
// find the length of the first string
for (i = 0; str1[i] != '\0'; i++);
// concatenate the second string to the end of the first string
for (j = 0; str2[j] != '\0'; j++) {
str1[i + j] = str2[j];
}
// add the null character to the end of the concatenated string
str1[i + j] = '\0';
printf("Concatenated string: %s", str1);
return 0;
}
```
这个程序使用两个字符数组来存储两个输入的字符串,然后使用两个循环来找到第一个字符串的长度和将第二个字符串连接到第一个字符串的末尾。最后,程序添加一个空字符到连接的字符串的末尾,并将其打印出来。
编一个程序,将两个字符串连接起来,不要用strcat函数
可以使用循环遍历字符串,将第一个字符串的每个字符依次复制到新的字符串中,然后再将第二个字符串的每个字符依次复制到新的字符串中。最后在新的字符串末尾添加一个结束符'\'。
示例代码:
```c
#include <stdio.h>
void my_strcat(char* dest, const char* src) {
while (*dest) { // 找到dest字符串的末尾
dest++;
}
while (*src) { // 复制src字符串到dest字符串末尾
*dest++ = *src++;
}
*dest = '\'; // 添加结束符
}
int main() {
char str1[20] = "hello";
char str2[] = "world";
my_strcat(str1, str2);
printf("%s\n", str1); // 输出"helloworld"
return ;
}
```
相关推荐
![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)