编写一个程序,将两个字符串连起来,不要用strcat函数,并返回连接后字符串长度
时间: 2025-01-24 08:09:43 浏览: 37
为了编写一个不使用`strcat`函数将两个字符串连接在一起的程序,并返回连接后的字符串长度,你可以创建一个新的数组,将两个字符串的字符逐个复制到新数组中。以下是使用C语言的一个简单示例:
```c
#include <stdio.h>
#include <string.h> // 需要这个头文件来获取strlen的功能,尽管我们不会直接使用它
void concatenate(char* dest, const char* src) {
int i = 0, j = 0;
while (src[i] != '\0') { // 遍历源字符串直到遇到结束符
dest[j++] = src[i]; // 复制字符
if (dest[j - 1] == '\0' && src[i] != '\0') { // 如果目标已到达结尾并且源未结束,添加空字符
dest[j] = '\0';
}
i++;
}
}
int get_combined_length(const char* str1, const char* str2) {
char combined[strlen(str1) + strlen(str2) + 2]; // 增加两个额外的空间,用于存储潜在的'\0'字符
concatenate(combined, str1);
concatenate(combined, str2);
return strlen(combined); // 返回新的组合字符串长度
}
int main() {
const char* str1 = "Hello, ";
const char* str2 = "world!";
char combined[length];
int length_result = get_combined_length(str1, str2);
printf("Combined string: %s\n", combined);
printf("Length of the combined string: %d\n", length_result);
return 0;
}
```
在这个例子中,`concatenate` 函数负责实际的拼接操作,而 `get_combined_length` 函数计算新的字符串长度。注意,我们在这里假设有足够的空间在`combined`数组中存放两个原始字符串及其终止符`\0`。
阅读全文
相关推荐

















