将一个字符数组连接到另一个字符数组的末尾(没有内置函数)
Concating a char array to the end of another char array (without built in functions)
我已经坚持了几个小时了,我需要将一个字符串连接到另一个字符串的末尾,然后将结果存储在第三个字符串中(不使用预构建的函数)。我很难尝试将我的结果存储到另一个字符串中,我能够瞥见我想要的东西,但它会导致无限循环,似乎并不有效。有人能解释一下吗?
#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 = ' ';
}
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符