c语言将两个字符串连接起来不要用strcat函数
时间: 2023-12-15 21:21:56 浏览: 33
可以使用循环将第二个字符串中的每个字符添加到第一个字符串的末尾,直到第二个字符串的结尾标志'\0'。例如:
```c
#include <stdio.h>
void mystrcat(char *s1, const char *s2) {
while (*s1) { // 找到s1的结尾
s1++;
}
while (*s2) { // 将s2中的字符添加到s1的末尾
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0'; // 添加字符串结尾标志
}
int main() {
char s1[20] = "Hello, ";
char s2[] = "world!";
mystrcat(s1, s2);
printf("%s\n", s1); // 输出Hello, world!
return 0;
}
```
相关问题
运用C语言将两个字符串连接起来,不要用strcat函数。
可以使用指针来实现字符串连接,示例代码如下:
```c
#include <stdio.h>
void my_strcat(char *s1, char *s2) {
// 将指针移动到s1的末尾
while (*s1 != '\0') {
s1++;
}
// 逐个将s2的字符添加到s1的末尾
while (*s2 != '\0') {
*s1 = *s2;
s1++;
s2++;
}
// 添加字符串结束符
*s1 = '\0';
}
int main() {
char s1[20] = "hello";
char s2[] = "world";
my_strcat(s1, s2);
printf("%s\n", s1); // 输出 "helloworld"
return 0;
}
```
在上面的代码中,我们先将指针移动到`s1`的末尾(即`\0`字符所在的位置),然后逐个将`s2`的字符添加到`s1`的末尾,最后再添加一个字符串结束符`\0`。这样就实现了字符串的连接。
通过C语言将两个字符串连接起来, 不要用字符串连接函数strcat函数。
可以通过循环遍历两个字符串并逐一复制到一个新的字符串中来实现字符串的连接,示例代码如下:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100], new_str[200];
int len1 = 0, len2 = 0, i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 计算两个字符串的长度
while (str1[len1] != '\0') {
len1++;
}
while (str2[len2] != '\0') {
len2++;
}
// 将两个字符串复制到新的字符串中
for (i = 0; i < len1; i++) {
new_str[i] = str1[i];
}
for (j = 0; j < len2; j++) {
new_str[i + j] = str2[j];
}
new_str[i + j] = '\0'; // 加上字符串结束符
printf("连接后的字符串为:%s", new_str);
return 0;
}
```
这样就能够通过C语言将两个字符串连接起来了。