gpt4 book ai didi

c - 使用分隔符连接 C 中的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:18 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来使用分隔符连接字符串。这是我目前所拥有的:

int main(void) {

char * strings[] = {"A", "B", NULL};
char ** copied_strings = malloc(sizeof strings);

// Join strings with a separator
char * separator = "XXX";
size_t num_array_elements = (sizeof strings / sizeof * strings) - 1; // because last element is NULL
size_t len_separator = strlen(separator);
size_t len_strings = 0;
for (int i=0; strings[i] != NULL ;i++) len_strings += strlen(strings[i]);
size_t malloc_buffer_size = len_strings + (len_separator * (num_array_elements -1)) + 1;
printf("Separator: %s | Len Array: %lu | Len Strings: %lu | Malloc Buffer Size: %lu\n", separator, num_array_elements, len_strings, malloc_buffer_size);
char * joined_string_buffer = malloc(malloc_buffer_size);
join_strings(joined_string_buffer, copied_strings, separator);

}

void join_strings(char * joined_string_buffer, char ** src, char * separator) {

size_t sep_len = strlen(separator);

while (*src) {
size_t string_len = strlen(*src);
for (int i=0; i<string_len; i++)
*joined_string_buffer++ = (*src)[i];
for (int i=0; i<sep_len; i++)
*joined_string_buffer++ = separator[i];
*src++;
}

*joined_string_buffer = '\0';

}

但是,我似乎没有正确地将字符复制到 *joined_string_buffer。我如何在此处正确加入字符串?

最佳答案

假设如果您要添加一个分隔符,您只想将分隔符放在您的strings 中的单词之间数组,您需要将条件逻辑添加到您的 join_stings函数仅在 strings 中的第二个(及后续)字符串之前添加分隔符数组。

有多种方法可以解决该问题,但考虑到您的 strings数组有一个哨兵 NULL ,你可以这样做:

char *joinstr (const char **s, const char *sep)
{
char *joined = NULL; /* pointer to joined string w/sep */
size_t lensep = strlen (sep), /* length of separator */
sz = 0; /* current stored size */
int first = 1; /* flag whether first term */

while (*s) { /* for each string in s */
size_t len = strlen (*s);
/* allocate/reallocate joined */
void *tmp = realloc (joined, sz + len + (first ? 0 : lensep) + 1);
if (!tmp) { /* validate allocation */
perror ("realloc-tmp"); /* handle error (adjust as req'd) */
exit (EXIT_FAILURE);
}
joined = tmp; /* assign allocated block to joined */
if (!first) { /* if not first string */
strcpy (joined + sz, sep); /* copy separator */
sz += lensep; /* update stored size */
}
strcpy (joined + sz, *s++); /* copy string to joined */
first = 0; /* unset first flag */
sz += len; /* update stored size */
}

return joined; /* return joined string */
}

添加短 main()测试 joinstr上面的函数,你可以这样做:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
...
int main (void) {

const char *strings[] = {"A", "B", NULL},
*sep = "XXX";
char *joined = joinstr (strings, sep); /* join strings */

printf ("%s\n", joined); /* output joined string */
free (joined); /* free memory */
}

示例使用/输出

$ ./bin/joinwsep
AXXXB

内存使用/错误检查

在您编写的任何动态分配内存的代码中,您对分配的任何内存块负有 2 个责任:(1) 始终保留指向起始地址的指针内存块,因此,(2) 它可以在不再需要时被释放

您必须使用内存错误检查程序来确保您不会尝试访问内存或写入超出/超出您分配的 block 的边界,尝试读取或基于未初始化的值进行条件跳转,最后, 以确认您释放了所有已分配的内存。

对于 Linux valgrind是正常的选择。每个平台都有类似的内存检查器。它们都易于使用,只需通过它运行您的程序即可。

$ valgrind ./bin/joinwsep
==17127== Memcheck, a memory error detector
==17127== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==17127== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==17127== Command: ./bin/joinwsep
==17127==
AXXXB
==17127==
==17127== HEAP SUMMARY:
==17127== in use at exit: 0 bytes in 0 blocks
==17127== total heap usage: 2 allocs, 2 frees, 8 bytes allocated
==17127==
==17127== All heap blocks were freed -- no leaks are possible
==17127==
==17127== For counts of detected and suppressed errors, rerun with: -v
==17127== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

始终确认您已释放所有分配的内存并且没有内存错误。

检查一下,如果您还有其他问题,请告诉我。

关于c - 使用分隔符连接 C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com