将两个字符串连接起来,不要用strcat函数。
时间: 2023-04-27 16:01:30 浏览: 64
可以通过遍历第一个字符串,在其结尾处添加第二个字符串的每一个字符来实现。代码示例:
```
#include <iostream>
#include <cstring>
int main() {
char str1[100] = "hello";
char str2[100] = ", world";
int len1 = strlen(str1);
int len2 = strlen(str2);
for (int i = 0; i <= len2; i++) {
str1[len1 + i] = str2[i];
}
std::cout << str1 << std::endl;
return 0;
}
```
输出: `hello, world`
相关问题
c语言将两个字符串连接起来不要用strcat函数
可以使用循环将第二个字符串中的每个字符添加到第一个字符串的末尾,直到第二个字符串的结尾标志'\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;
}
```
将两个字符串连接起来,不用strcat函数
你好,关于你的问题,可以使用以下代码将两个字符串连接起来:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[20] = "Hello";
char str2[20] = " World!";
int i = 0, j = 0;
while (str1[i] != '\0') {
i++;
}
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0'; // 添加字符串结束符
cout << str1 << endl;
return 0;
}
```
上述代码中,首先将指针 `i` 和 `j` 初始化为 0,然后使用 `while` 循环找到字符串 `str1` 的末尾位置。接着使用另一个 `while` 循环,逐个将 `str2` 中的字符添加到 `str1` 的末尾,直到 `str2` 的末尾位置。最后,在 `str1` 的末尾添加字符串结束符 `\0`,以表示字符串的结束。最终,使用 `cout` 输出拼接后的字符串 `str1`。
希望能解答您的问题。