C语言定义两个指针变量,分别指向字符串Long live和China,然后调用字符串连接函数,将两个字符串进行连接,最后用%s格式符输出连接后的字符串。
时间: 2024-02-19 20:57:47 浏览: 25
好的,下面是实现这个功能的C语言代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Long live";
char str2[] = "China";
char str3[100];
strcpy(str3, str1);
strcat(str3, str2);
printf("%s\n", str3);
return 0;
}
```
代码中首先定义了两个字符数组`str1`和`str2`,分别存储字符串"Long live"和"China"。然后定义了一个字符数组`str3`,用来存储连接后的字符串。接着使用`strcpy`函数将`str1`复制到`str3`中,再使用`strcat`函数将`str2`连接到`str3`的末尾。最后使用`printf`函数打印输出`str3`即可。
相关问题
用c语言写一个输入两个字符串并用char函数定义后将字符串连接的代码
下面是一个示例代码,可以让用户输入两个字符串,然后使用char函数将它们连接起来:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
strcat(str1, str2); // 使用 strcat 函数将两个字符串连接起来
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
在上述代码中,我们首先定义了两个字符数组 `str1` 和 `str2`,用于存储用户输入的两个字符串。然后,使用 `scanf` 函数分别读取用户输入的两个字符串。
接下来,我们使用 `strcat` 函数将两个字符串连接起来,并将结果保存在 `str1` 中。最后,通过 `printf` 函数将连接后的字符串输出到屏幕上。
C语言定义两个指针变量,分别指向字符串“Long live”和“China”,然后用指针变量作为函数参数,调用自编的字符串连接函数(函数名为str_cat,函数参数为两个字符指针变量),将两个字符串连接,最后通过printf函数,使用%s格式符将连接后的字符串输出。
好的,下面是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void str_cat(char *dest, char *src) {
while (*dest) {
dest++;
}
while (*src) {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}
int main() {
char *str1 = "Long live";
char *str2 = "China";
char *result = (char *)malloc(strlen(str1) + strlen(str2) + 1);
if (result == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
str_cat(result, str1);
str_cat(result, str2);
printf("%s\n", result);
free(result);
return 0;
}
```
运行结果为:
```
Long liveChina
```