(4) 功能:编写函数void len_cat(char c1[],char c2[])将第二个串连接到第一个串之后,不允许使用strcat函数。
时间: 2023-11-27 15:52:41 浏览: 49
可以使用以下代码实现:
```c
#include <stdio.h>
void len_cat(char c1[], char c2[]) {
int i = 0, j = 0;
while (c1[i] != '\0') {
i++;
}
while (c2[j] != '\0') {
c1[i] = c2[j];
i++;
j++;
}
c1[i] = '\0';
}
int main() {
char str1[100] = "hello";
char str2[] = "world";
len_cat(str1, str2);
printf("%s", str1);
return 0;
}
```
首先,在函数中定义两个变量 `i` 和 `j` 分别表示 `c1` 和 `c2` 的下标,初始化为 0。然后在第一个 while 循环中,找到字符串 `c1` 的结尾,即遍历到了字符串末尾的空字符 `\0`。接着在第二个 while 循环中,将字符串 `c2` 的每一个字符都追加到字符串 `c1` 的结尾。最后,在字符串末尾添加一个空字符 `\0` 表示字符串的结束。
在主函数中,我们定义了两个字符数组 `str1` 和 `str2`,并将 `str2` 的内容追加到 `str1` 的末尾。最后,使用 `printf` 函数打印出连接后的字符串 `str1`。
相关问题
c语言编写函数void my_strcat(char str1[],char str2[]),实现字符串连接。
C语言中的函数void my_strcat(char str1[],char str2[])可以实现字符串连接。该函数的实现过程如下:
1. 首先判断输入的两个字符串是否为空,如果为空则直接返回。
2. 将指针str1指向字符串s1的末尾。
3. 将字符串s2中的字符逐个复制到字符串s1的末尾,直到字符串s2的末尾。
4. 在字符串s1的末尾添加'\0',表示字符串的结束。
下面是该函数的代码实现:
void my_strcat(char str1[], char str2[]) {
int i = 0, j = 0;
while (str1[i] != '\0') {
i++;
}
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';
}
使用该函数可以将两个字符串连接起来,例如:
char str1[100] = "hello";
char str2[100] = "world";
my_strcat(str1, str2);
printf("%s", str1); //输出"helloworld"
编写一函数 将字符串2连接到字符串一后面 不能使用strcat函数 函数首部为void_cat(char str1[] char str 2[]
下面是一个实现将字符串2连接到字符串1后面的函数,不使用strcat函数:
```
void cat(char str1[], char str2[]) {
int i = 0, j = 0;
while (str1[i] != '\0') {
i++;
}
while (str2[j] != '\0') {
str1[i++] = str2[j++];
}
str1[i] = '\0';
}
```
这个函数首先找到字符串1的结尾,然后将字符串2中的每个字符复制到字符串1的结尾处,直到遇到字符串2的结尾符'\0'。最后,将字符串1的新结尾也设置为'\0'。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)