c语言连接两个字符串不用strcat
时间: 2023-06-05 14:07:54 浏览: 75
可以使用strcpy和strlen函数来连接两个字符串。具体实现方法如下:
1.先定义一个足够大的数组来存储两个字符串连接后的结果,如下:
char result[MAXSIZE];
2.使用strcpy函数将第一个字符串拷贝到result数组中,如下:
strcpy(result, str1);
3.使用strlen函数获取第一个字符串的长度,计算出第二个字符串需要拷贝的起始位置,如下:
int len1 = strlen(str1);
strcpy(result + len1, str2);
4.最后,result数组中存储的就是两个字符串连接后的结果,如下:
printf("%s", result);
相关问题
用c语言连接两个字符串
您可以使用C语言中的字符串拼接函数 strcat() 来连接两个字符串。
下面是一个使用 strcat() 函数连接两个字符串的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[20] = "world!";
strcat(str1, str2);
printf("%s", str1);
return 0;
}
```
运行结果为:
```
Hello, world!
```
在上面的示例代码中,我们首先定义了两个字符数组 str1 和 str2,分别存储了两个需要连接的字符串。然后使用 strcat() 函数将 str2 的内容连接到 str1 中,最后输出连接后的结果。
需要注意的是,使用 strcat() 函数进行字符串连接时,请确保目标字符数组(即第一个参数)具有足够的空间来存储连接后的结果。
c语言连接两个字符串
在C语言中连接两个字符串可以使用strcat()函数。该函数的原型为:
```c
char *strcat(char *dest, const char *src);
```
其中,dest是目标字符串,src是被连接的字符串,函数返回一个指向目标字符串的指针。使用该函数时,要确保目标字符串dest有足够的空间来容纳被连接的字符串src。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "hello";
char str2[20] = "world";
strcat(str1, str2);
printf("str1 = %s\n", str1);
return 0;
}
```
输出结果为:`str1 = 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)