将一个字符数组连接到另一个字符数组的末尾(没有内置函数)

Concating a char array to the end of another char array (without built in functions)

本文关键字:数组 字符 函数 内置 连接 一个 另一个      更新时间:2023-10-16

我已经坚持了几个小时了,我需要将一个字符串连接到另一个字符串的末尾,然后将结果存储在第三个字符串中(不使用预构建的函数)。我很难尝试将我的结果存储到另一个字符串中,我能够瞥见我想要的东西,但它会导致无限循环,似乎并不有效。有人能解释一下吗?

#include <iostream>
using namespace std;
void Concat(char arr1[], char arr2[], char arr3[]);
int main(){
    char arr1[] = {"Hello how are you?  "};
    char arr2[] = { "The weather was cloudy today, so it rained. " };
    char arr3[] = { "Coffee is a great way to start the day. " };
    Concat(arr1, arr2, arr3);
}
void Concat(char arr1[], char arr2[], char arr3[]){
    while (arr1 != '' && arr2 != '') {
        // (This outputs what a want, haveing string 2 concat to the end of the firs string) 
        // However there is no way to save it to another array or stop the infinte loop.
        //cout << arr1 << arr2 << endl; 
        arr1 + arr2 = arr3; // syntax error
    }

} 

你可以试试这样做:

#include <iostream>
void concat(const char *arr1, const char *arr2, char *arr3);
int main(){
    const char *arr1("abc");
    const char *arr2("def");
    char arr3[10];
    concat(arr1, arr2, arr3);
    std::cout << "arr3 is " << arr3 << std::endl;
}
void concat(const char *arr1, const char *arr2, char *arr3){
    if (arr1) {
        while(*arr1 != '') {
            *arr3 = *arr1;
            ++arr1; ++arr3;
        }
    }
    if (arr2) {
        while(*arr2 != '') {
            *arr3 = *arr2;
            ++arr2; ++arr3;
        }
    }
    *arr3 = '';
}

快速解决你的问题:

void Concat(const char* input1, const char* input2, char* output)
{
    int i = 0;
    do {
        output[i] = *input1;
        i++;
        input1++;
    } while (*input1 != '');
    do {
        output[i] = *input2;
        i++;
        input2++;
    } while (*input2 != '');
}

注意:我没有检查输出缓冲区是否有足够的内存和其他,我希望你可以自己编辑它。

您应该尝试逐个索引连接。在下面的代码中,我首先将arr1的所有内容添加到arr3中,然后将arr2的内容与arr3连接

#include <iostream>
using namespace std;
void Concat(char arr1[], char arr2[], char arr3[]);
int main(){
    char arr1[] = {"Hello how are you?  "};
    char arr2[] = { "The weather was cloudy today, so it rained. " };
    char arr3[] = { "Coffee is a great way to start the day. " };
    Concat(arr1, arr2, arr3);
    std::cout << "arr3 is " << arr3 << std::endl;
}
void Concat(char arr1[], char arr2[], char arr3[]){
   if (arr1) {
        while(*arr1 != '') {
            *arr3 = *arr1;
            ++arr1; ++arr3;
        }
    }
    if (arr2) {
        while(*arr2 != '') {
            *arr3 = *arr2;
            ++arr2; ++arr3;
        }
    }
    *arr3 = '';

}