不用strcat字符叠加
时间: 2023-07-29 07:12:18 浏览: 40
如果你想将一个字符串添加到另一个字符串末尾,可以使用strcpy和strlen函数来实现。具体步骤如下:
1. 使用strlen函数获取目标字符串的长度;
2. 使用strcpy函数将源字符串复制到目标字符串的末尾;
3. 确保目标字符串以'\0'结尾。
以下是一个示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
char src[] = " World!";
int dest_len = strlen(dest);
strcpy(dest + dest_len, src);
printf("%s", dest);
return 0;
}
```
输出结果为:Hello World!
相关问题
不用strcat连接两个字符串
不用strcat连接两个字符串可以使用其他方法,比如使用sprintf函数将两个字符串合并成一个新的字符串。另外,也可以使用指针来遍历两个字符串,将第一个字符串的字符逐个复制到新的字符串中,然后再复制第二个字符串的字符。还可以使用字符串处理函数如strcpy和strncpy来实现字符串的连接。另外,还可以使用字符串数组来存储两个字符串,然后使用循环遍历数组来将两个字符串连接在一起。总之,不用strcat连接两个字符串有很多方法,可以根据具体情况选择合适的方法来实现字符串的连接。
不用strcat函数实现字符串的连接
以下是两种不使用strcat函数实现字符串连接的方法:
方法一:使用指针
```c
#include <stdio.h>
void str_concat(char *s1, char *s2) {
while (*s1) { // 找到s1的结尾
s1++;
}
while (*s2) { // 将s2的字符逐个复制到s1的结尾
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0'; // 在s1的结尾添加'\0'
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
str_concat(s1, s2);
printf("%s\n", s1); // 输出:helloworld
return 0;
}
```
方法二:使用数组下标
```c
#include <stdio.h>
void str_concat(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'; // 在s1的结尾添加'\0'
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
str_concat(s1, s2);
printf("%s\n", s1); // 输出:helloworld
return 0;
}
```