2. 编写一个函数,将两个字符串连接起来,不能使用strcat函数。
时间: 2023-12-15 12:19:18 浏览: 27
可以使用以下函数实现字符串连接:
```c
#include <stdio.h>
void my_strcat(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[100] = "world";
my_strcat(s1, s2);
printf("%s\n", s1); // 输出 "helloworld"
return 0;
}
```
该函数的实现原理是先找到第一个字符串的末尾,然后将第二个字符串从该位置开始逐个字符复制到第一个字符串的末尾,直到第二个字符串的末尾。最后在第一个字符串的末尾添加一个空字符'\0',以表示字符串的结束。
相关问题
2. 编写一个函数,将两个字符串连接起来,不能使用strcat函数。
可以使用循环来完成字符串的连接,具体实现如下:
```c
#include <stdio.h>
void my_strcat(char* dest, const char* src) {
while (*dest) {
dest++;
}
while (*src) {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}
int main() {
char str1[50] = "Hello, ";
char str2[] = "world!";
my_strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
在这个实现中,我们使用两个while循环,第一个while循环找到dest字符串的末尾,第二个while循环将src字符串中的字符逐个拷贝到dest字符串的末尾,并且在最后加上'\0',表示字符串的结束。
2.编写一个程序,将两个字符串连接起来,不要用strcat函数
以下是一个不使用strcat函数的程序,将两个字符串连接起来:
```c
#include <stdio.h>
#include <string.h>
void my_strcat(char* s1, char* s2);
int main() {
char str1[50], str2[50];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
my_strcat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
void my_strcat(char* s1, char* s2) {
int len1 = strlen(s1);
int len2 = strlen(s2);
for (int i = 0; i < len2; i++) {
s1[len1 + i] = s2[i];
}
s1[len1 + len2] = '\0';
}
```