尝试将 c 字符串数组与分隔符连接起来

Trying to concatenate array of c-strings with delimiter

本文关键字:分隔符 连接 起来 数组 字符串      更新时间:2023-10-16

这是我的代码

int main(int argc, char *argv[]) {
char const *strings[10] = {"dhh", "aci", "cdh"};
join_def(strings, 'l');
return EXIT_SUCCESS;
}

// part 1 read lines
void join_def(char const **strings, char delim) {
char *t = new char[100];
//int length = 0;
t[0] = '';
int x = sizeof(strings);
std::cout << delim << std::endl;
for (int i = 0; i < x; i++) {
int size = 0;
while(strings[i][size]!=''){
size++;
std::cout << strings[i][size] << std::endl;
}
}
}

我已经花了几个小时了,我只是无法连接它 对于此任务,我不能使用 cstring 或 iostream 以外的任何东西,所以请不要建议。

输出需要是一个 c 字符串 = "dhhlacilcdh">

首先,您无法确定传递给函数的数组中的元素数,因为该数组将衰减为简单的指针。因此,您的sizeof(strings)表达式将(在编译时(计算指针的(固定(大小(以字节为单位(。为了使函数"知道"数组中有多少元素,需要显式告诉它(通过额外的参数(。

其次,您的i' 和size索引在std::cout << strings[i][size] << std::endl;行中以错误的方式进行,此外,您在打印相关字符之前递增size,而在打印应该递增。

下面的代码还执行字符串的实际连接,修改后的join_def函数现在返回指向该结果的指针(完成后必须释放该指针(;

#include <iostream>
char* join_def(char const** strings, char delim, int x)
{
char* t = new char[100];
int length = 0;
t[0] = '';
//int x = sizeof(strings);
std::cout << delim << std::endl;
for (int i = 0; i < x; i++) {
int size = 0;
while (strings[i][size] != '') {
std::cout << strings[i][size] << std::endl;
t[length++] = strings[i][size]; // Append this character
size++;
}
t[length++] = delim; // Append delimiter
}
t[length] = ''; // Append nul-terminator
return t;
}
int main()
{
char const* strings[10] = { "dhh", "aci", "cdh" };
char* result = join_def(strings, 'l', 3);
std::cout << result << std::endl;
free(result);
return 0;
}

另请注意,我已将join_def函数代码移动到main(调用它(之前。如果你不这样做,那么至少必须在main之前提供该函数的(前向(声明(只是一个char* join_def(char const** strings, char delim, int x);本身就可以了(。

请随时要求进一步澄清和/或解释。

我不确定你想做什么,但也许这会有所帮助?

#include <iostream>
// part 1 read lines
void join_def(char const **strings, char delim)
{
char *t = new char[100];
//int length = 0;
t[0] = '';
int x = 0;
for (int i = 0; strings[i] != nullptr; i++)
x += sizeof(strings[i]) - 1;

std::cout << delim << std::endl;
for (int i = 0; strings[i] != nullptr; i++)
{
int size = 0;
while (strings[i][size] != '')
{
size++;
std::cout << strings[i][size] << std::endl;
}
}
}
int main(int argc, char *argv[])
{
char const *strings[] = {"dhh", "aci", "cdh", nullptr};
join_def(strings, 'l');
return EXIT_SUCCESS;
}

这就是你要找的吗? 看起来我删除了所有std::endl,因为它喜欢'n'我也在std::cout之后移动了你的size++

#include <iostream>

// part 1 read lines
void join_def(char const **strings, char delim,int length) {
char *t = new char[100];
//int length = 0;
t[0] = '';
int x = length;

for (int i = 0; i < x; i++) {
int size = 0;
while(strings[i][size]!=''){
std::cout << strings[i][size]; //<--print befure increment size
size++;
}
std::cout << delim;
}
}


int main(int argc, char *argv[]) {
char const *strings[] = {"dhh", "aci", "cdh"};
join_def(strings,'|',3); //<- need to send the length of the char* array
return EXIT_SUCCESS;
}