用c语言编写自定义函数void tailAppend(char s1[],char s2[]),,其功能是将字符串s2接到字符串s1之后(不调用strcpy或strcat函数)。例如:若字符串s1为"abcd",字符串s2为:"1mn",将s2串接到s1之后,字符串s1为:"abcd1mn"的代码
时间: 2024-02-03 12:14:57 浏览: 27
下面是实现该功能的代码:
```c
void tailAppend(char s1[], char s2[]) {
int i = 0, j = 0;
while (s1[i] != '\0') { // 找到s1的末尾位置
i++;
}
while (s2[j] != '\0') { // 将s2接到s1的末尾
s1[i] = s2[j];
i++;
j++;
}
s1[i] = '\0'; // 添加末尾的'\0'字符
}
```
使用方法如下:
```c
int main() {
char s1[100] = "abcd";
char s2[100] = "1mn";
tailAppend(s1, s2);
printf("%s\n", s1); // 输出"abcd1mn"
return 0;
}
```
相关问题
用c语言编写自定义函数void tailAppend(char s1[],char s2[]),,其功能是将字符串s2接到字符串s1之后(不调用strcpy或strcat函数)
下面是一个用C语言编写的自定义函数`void tailAppend(char s1[], char s2[])`,可以将字符串s2接到字符串s1之后:
```c
#include <stdio.h>
void tailAppend(char s1[], char s2[]) {
int i, j;
for (i = 0; s1[i] != '\0'; i++) {} // 找到s1的结尾
for (j = 0; s2[j] != '\0'; j++) {
s1[i + j] = s2[j]; // 将s2中的字符一个个拷贝到s1的结尾后
}
s1[i + j] = '\0'; // 注意字符串结尾符号
}
int main() {
char s1[100] = "hello, ";
char s2[] = "world!";
tailAppend(s1, s2);
printf("%s\n", s1); // 输出 "hello, world!"
return 0;
}
```
这个函数的实现方法很简单,就是先找到s1的结尾,然后从s2的开头一个个拷贝字符到s1的结尾后,并在最后加上字符串结尾符'\0'。需要注意的是,s1数组必须要有足够的空间来存放新的字符串,否则可能会导致内存溢出等问题。
用c语言编写自定义函数完成两个字符串的连接功能,要求自定义函数形参采用指针。
可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
void mystrcat(char *s1, char *s2) {
while (*s1 != '\0') {
s1++;
}
while (*s2 != '\0') {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char s1[100] = "Hello";
char s2[] = "World";
mystrcat(s1, s2);
printf("%s\n", s1);
return 0;
}
```
在上面的代码中,`mystrcat` 函数接受两个指向字符数组的指针 `s1` 和 `s2`,并将 `s2` 中的字符连接到 `s1` 的末尾。函数的实现相当简单,只需使用指针逐个字符地复制 `s2` 中的字符到 `s1` 中,直到 `s2` 的末尾,并在 `s1` 的末尾添加一个空字符来终止字符串。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)