两个字符串连接-调用自定义函数
时间: 2023-08-02 15:16:04 浏览: 112
假设你要连接两个字符串s1和s2,可以自定义一个函数concatenate(s1, s2),实现字符串的连接操作。具体代码如下:
```
def concatenate(s1, s2):
return s1 + s2
s1 = "Hello"
s2 = "World"
result = concatenate(s1, s2)
print(result)
```
运行结果为:
```
HelloWorld
```
相关问题
两个字符串连接-调用自定义函数 分数 10 作者 崔孝凤 单位 山东理工大学 两个字符串连接,在主函数中输入两个字符串,调用函数myscat完成两个字符串的连接,最后输出连接后的字符串,请在程序空白处填写合适的语句以
完成程序。
```c
#include <stdio.h>
#include <string.h>
void myscat(char dest[], char src[]) {
int len_dest = strlen(dest);
int i;
for (i = 0; src[i] != '\0'; i++) {
dest[len_dest + i] = src[i];
}
dest[len_dest + i] = '\0';
}
int main() {
char str1[100], str2[100];
scanf("%s %s", str1, str2);
myscat(str1, str2);
printf("%s", str1);
return 0;
}
```
自定义函数实现两个字符串的连接。要求函数返回值是连接后的字符串。 主函数接收从键盘输入的两行不超过80个字符的字符串(包括空格),调用自定义函数实现字符串的连接。 注意自定义函数中的第1个字符数组长度必须足够大。
好的,根据您提供的代码,我为您续写完整的代码如下:
```c
#include <stdio.h>
#include <string.h>
char* str_cat(char *a, char *b);
const int N = 82;
int main() {
char s1[N*3], s2[N], s3[N*4];
fgets(s1, N, stdin); //最多接收N-1个字符,包括回车
s1[strlen(s1) - 1] = 0;
fgets(s2, N, stdin);
s2[strlen(s2) - 1] = 0;
char *result = str_cat(s1, s2);
printf("连接后的字符串为:%s\n", result);
return 0;
}
char* str_cat(char *a, char *b) {
int len_a = strlen(a);
int len_b = strlen(b);
char *c = (char*)malloc((len_a + len_b + 1) * sizeof(char));
int i, j;
for (i = 0; i < len_a; i++) {
c[i] = a[i];
}
for (j = 0; j < len_b; j++) {
c[i+j] = b[j];
}
c[i+j] = '\0';
return c;
}
```
该程序中,`str_cat()` 函数实现了两个字符串的连接,并返回连接后的字符串。主函数中,我们从键盘输入两个字符串 `s1` 和 `s2`,然后调用 `str_cat()` 函数进行连接,最后输出连接后的结果。需要注意的是,我们在输入字符串后需要将回车符去掉,否则会影响字符串连接的结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)