不用strcat函数实现将字符串t连接到字符串s的后面
时间: 2023-10-04 17:09:33 浏览: 109
可以使用指针来实现将字符串t连接到字符串s的后面,具体实现如下:
```c
void my_strcat(char *s, char *t) {
while (*s) { // 找到s的结尾
s++;
}
while ((*s++ = *t++)) { // 将t复制到s的结尾
;
}
}
```
首先找到字符串s的结尾,然后将字符串t复制到s的结尾。在这个过程中,使用了指针的自增运算符来遍历字符串。
相关问题
不用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;
}
```
C语言不用指针不用strcat函数实现两个字符串的连接。
在 C 语言中,可以使用数组来操作字符串,从而实现字符串的连接。以下是一种实现方法:
```c
#include <stdio.h>
void string_concat(char dest[], char src[]) {
int i, j;
i = j = 0;
// 指针移动到 dest 的末尾
while (dest[i] != '\0') {
i++;
}
// 将 src 复制到 dest 的末尾
while (src[j] != '\0') {
dest[i] = src[j];
i++;
j++;
}
// 添加字符串结束标志
dest[i] = '\0';
}
int main() {
char str1[100] = "hello";
char str2[50] = "world";
// 连接两个字符串
string_concat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
以上代码中,`string_concat()` 函数接受两个字符串数组 `dest` 和 `src`,然后将 `src` 中的字符复制到 `dest` 的末尾,并在末尾添加字符串结束标志 '\0',从而实现字符串的连接。最后在 `main()` 函数中,调用 `string_concat()` 函数来连接两个字符串,并输出连接后的字符串。