c语言将两个字符串连接起来的函数
时间: 2023-11-30 17:02:39 浏览: 94
C语言中将两个字符串连接起来的函数是strcat(),函数原型如下:
```c
char *strcat(char *dest, const char *src);
```
其中,dest是目标字符串,src是源字符串,函数会将源字符串拼接到目标字符串的末尾,并返回目标字符串的指针。
需要注意的是,目标字符串必须足够大,能够容纳新加入的源字符串,否则可能会导致缓冲区溢出的问题。
以下是一个使用strcat()函数将两个字符串连接起来的例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
char src[] = "World";
strcat(dest, src);
printf("%s\n", dest);
return 0;
}
```
输出结果为:
```
HelloWorld
```
相关问题
c语言将两个字符串连接起来不要用strcat函数
可以使用循环将第二个字符串中的每个字符添加到第一个字符串的末尾,直到第二个字符串的结尾标志'\0'。例如:
```c
#include <stdio.h>
void mystrcat(char *s1, const char *s2) {
while (*s1) { // 找到s1的结尾
s1++;
}
while (*s2) { // 将s2中的字符添加到s1的末尾
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0'; // 添加字符串结尾标志
}
int main() {
char s1[20] = "Hello, ";
char s2[] = "world!";
mystrcat(s1, s2);
printf("%s\n", s1); // 输出Hello, world!
return 0;
}
```
通过C语言将两个字符串连接起来, 不要用字符串连接函数strcat函数。
可以通过循环遍历两个字符串并逐一复制到一个新的字符串中来实现字符串的连接,示例代码如下:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100], new_str[200];
int len1 = 0, len2 = 0, i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 计算两个字符串的长度
while (str1[len1] != '\0') {
len1++;
}
while (str2[len2] != '\0') {
len2++;
}
// 将两个字符串复制到新的字符串中
for (i = 0; i < len1; i++) {
new_str[i] = str1[i];
}
for (j = 0; j < len2; j++) {
new_str[i + j] = str2[j];
}
new_str[i + j] = '\0'; // 加上字符串结束符
printf("连接后的字符串为:%s", new_str);
return 0;
}
```
这样就能够通过C语言将两个字符串连接起来了。