C语言不用strcat,将两个字符串连接
时间: 2023-12-21 22:05:47 浏览: 70
可以使用指针来实现两个字符串的连接,具体实现代码如下:
```c
#include <stdio.h>
void connect(char *s1, char *s2) {
while (*s1 != '\0') {
s1++;
}
while (*s2 != '\0') {
*s1++ = *s2++;
}
*s1 = '\0';
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
connect(s1, s2);
printf("%s\n", s1); // 输出 "helloworld"
return 0;
}
```
在这个实现中,我们定义了一个`connect`函数,该函数接受两个指向字符串的指针作为参数,然后使用两个`while`循环将第二个字符串中的字符添加到第一个字符串的末尾。注意,我们还添加了一个空字符`\0`来标记字符串的结束。最后,在`main`函数中我们调用`connect`函数并输出连接后的字符串。
相关问题
c语言不用strcat怎么把俩字符串连接起来
在C语言中,如果不使用`strcat()`函数直接将两个字符串连接起来,你可以选择手动操作字符数组。以下是一种简单的方法:
```c
#include <stdio.h>
#include <string.h>
// 自定义函数用于字符串连接
void string_concat(char* destination, const char* source) {
int i = strlen(destination); // 获取destination字符串长度
while (source[i] != '\0') { // 检查源字符串是否结束
destination[i++] = source[i]; // 将源字符串的每个字符复制到目标字符串
}
destination[i] = '\0'; // 在目标字符串末尾添加空字符表示结束
}
int main() {
char str1[50], str2[] = " is connected manually.";
printf("Original strings:\n");
fgets(str1, sizeof(str1), stdin); // 用户输入第一个字符串
// 连接字符串
string_concat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
```
在这个例子中,我们首先获取`destination`字符串的长度,然后逐个复制`source`字符串中的字符到`destination`,直到遇到`\0`为止。最后,在目标字符串的末尾添加一个终止符。
不用strcat将两个字符串连接起来
以下是一个不使用strcat函数将两个字符串连接起来的C语言代码示例:
```c
#include <stdio.h>
#include <string.h>
#define N 30
#define M 10
int main() {
int i, j;
char a[N] = {'\0'}, b[M] = {'\0'};
puts("输入第一个字符串:");
gets(a);
puts("输入第二个字符串:");
gets(b);
/*----将第二个字符串接在第一个字符串后----*/
for (i = strlen(a) / sizeof(a[0]), j = 0; j < strlen(b) / sizeof(b[0]); i++, j++) {
a[i] = b[j];
}
puts("两字符串链接后为:");
puts(a);
return 0;
}
```
阅读全文
相关推荐














