gpt4 book ai didi

c - 将一个字符串分成一定数量的子串(C)

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

因此,我读取了某个文件作为输入并将其加载到内存中,并获得了一个 cstring char* 文本。

我想将该字符串拆分为一定数量的字符串。例如,假设我有 4 个线程,我希望每个线程打印字符串的某个“片段”(不一定按顺序)。

int num_threads = 4;
char *filename = "file.txt";
int file_size = load_file_to_mem(filename, &text); // I made this and it works.
int text_size = strlen(text);
int substring_size; // that would be the size of each substring
char to_thread[num_threads][block_size];

如何将 *text 字符串拆分为 4 个相同大小的子字符串,也就是说,如何找到 block 大小以便让每个线程接收该大小的子字符串?

最佳答案

除非我误解了这个问题,否则一种方法是使用 ceil()函数:num_threads - 1 每个子字符串的长度都是 ceil(test_size/num_threads) + 1。剩余的单个子字符串的长度为 test_size - (num_threads - 1) * ceil(test_size/num_threads) + 1

您可能会这样做,因为 num_threads 可能不会将 test_size 平均分配。添加一个字节以包含每个子字符串的空终止符的空间。

关于c - 将一个字符串分成一定数量的子串(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32596494/

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