使用指针连接两个字符串:定义函数connect()连接两个字符串。main()中调用connect()连接两个字符串,并输出。
时间: 2023-04-28 07:01:56 浏览: 84
可以使用指针连接两个字符串,具体实现如下:
```
#include <stdio.h>
#include <string.h>
void connect(char *str1, char *str2) {
strcat(str1, str2);
}
int main() {
char str1[100] = "Hello, ";
char str2[] = "world!";
connect(str1, str2);
printf("%s\n", str1);
return 0;
}
```
在上面的代码中,我们定义了一个函数`connect`,它接受两个指向字符数组的指针`str1`和`str2`,并使用`strcat`函数将`str2`连接到`str1`的末尾。在`main`函数中,我们定义了两个字符串`str1`和`str2`,并将它们传递给`connect`函数进行连接。最后,我们输出连接后的字符串`str1`。
运行上面的代码,输出结果为:
```
Hello, world!
```
这说明我们成功地使用指针连接了两个字符串。
相关问题
编写自定义函数完成两个字符串的连接功能,要求自定义函数形参采用指针。
好的,下面是一个示例代码:
```c
#include<stdio.h>
#include<string.h>
void connect(char *str1, char *2, char *result){
// 将str1和str2拼接到result中
int i = 0, j = 0;
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
while (str2[j] != '\0') {
result[i+j] = str2[j];
j++;
}
result[i+j] = '\0'; // 结尾需要加上'\0'
}
int main() {
char str1[20] = "hello";
char str2[20] = "world";
char result[40];
connect(str1, str2, result);
printf("%s\n", result); // 输出结果:helloworld
return 0;
}
```
以上代码中,自定义函数 `connect` 接收三个参数:`char *str1`,`char *str2` 和 `char *result`,分别表示需要连接的两个字符串和连接后的结果字符串。函数通过指针的方式操作字符串,将 `str1` 和 `str2` 拼接到 `result` 中,并在结尾处添加了 `\0`,最后返回拼接后的结果。在主函数中,我们声明了需要拼接的两个字符串 `str1` 和 `str2`,并声明了一个足够大的字符数组 `result` 存储拼接后的结果。最后调用 `connect` 函数将两个字符串拼接到 `result` 中,并输出结果。
C语言不用strcat,将两个字符串连接
可以使用指针来实现两个字符串的连接,具体实现代码如下:
```c
#include <stdio.h>
void connect(char *s1, char *s2) {
while (*s1 != '\0') {
s1++;
}
while (*s2 != '\0') {
*s1++ = *s2++;
}
*s1 = '\0';
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
connect(s1, s2);
printf("%s\n", s1); // 输出 "helloworld"
return 0;
}
```
在这个实现中,我们定义了一个`connect`函数,该函数接受两个指向字符串的指针作为参数,然后使用两个`while`循环将第二个字符串中的字符添加到第一个字符串的末尾。注意,我们还添加了一个空字符`\0`来标记字符串的结束。最后,在`main`函数中我们调用`connect`函数并输出连接后的字符串。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)