编一程序,将两个字符串连接起来,不要用 strcat 函数。
时间: 2023-04-27 16:05:39 浏览: 55
可以使用循环和指针来实现字符串的连接,具体步骤如下:
1. 定义两个字符串,分别为 str1 和 str2。
2. 定义一个新的字符串,用于存储连接后的结果,例如 result。
3. 使用指针遍历 str1,将其中的每个字符逐个复制到 result 中。
4. 使用指针遍历 str2,将其中的每个字符逐个复制到 result 中。
5. 在 result 的末尾添加一个字符串结束符 '\0'。
6. 输出 result。
下面是示例代码:
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] = "world";
char result[11]; // 两个字符串长度之和加上一个字符串结束符
char *p1 = str1;
char *p2 = str2;
char *p3 = result;
while (*p1 != '\0') {
*p3 = *p1;
p1++;
p3++;
}
while (*p2 != '\0') {
*p3 = *p2;
p2++;
p3++;
}
*p3 = '\0'; // 添加字符串结束符
printf("%s", result);
return 0;
}
相关问题
编一程序,将两个字符串连接起来,不要用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函数;
好的,这个问题很简单。下面是一个使用 strcat 函数的示例程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World!";
strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
这个程序会将 "Hello" 和 "World!" 两个字符串连接起来,并输出结果 "HelloWorld!"。
相关推荐
![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)