gpt4 book ai didi

c - 在 C 中对二维数组的行进行排序

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

我正在尝试按字母顺序对二维数组中的每一行进行排序。我正在从一个文件中读入,我可以做到这一点:

int n_char = 0;
int charCount = 0, wordCount = 0, lineCount = 0;
int wordsPerLine[100];

char buffer;
char words[50][75];

wordsPerLine[0] = 0;
while( (n_char = read(fileDescriptor, &buffer, sizeof(char))) != 0) {


if (buffer == '\n' || buffer == ' ') {

words[wordCount][charCount] = '\0';
charCount = 0;
wordCount++;
wordsPerLine[lineCount] += 1;
if (buffer == '\n') {
lineCount++;
wordsPerLine[lineCount] = 0;
}

} else {

words[wordCount][charCount++] = buffer;


}
}

所有的单词和行都读得很好,但现在我在对行进行排序时遇到了问题。我知道每一行有多少个单词,我也知道数组中有多少行,所以现在我正在对所有单词进行连续计数,并记下新行的第一个单词。我的问题是如何对所有行进行排序?

到目前为止我只有这个:

int runningSize = 0;
for(i = 0; i < lineCount; i++) {
printf("%d\n", runningSize);
printf("\t%s\n", words[runningSize]);
runningSize += wordsPerLine[i];
}

如果不清楚,这里有一个例子:

输入:

hello world
goodbye world
elephants are really cool

预期输出:

elephants are really cool
goodbye world
hello world

最佳答案

为什么要重新发明轮子。您可以使用其中一种包含的排序算法来为您完成此操作。以下示例显示如何使用 qsort 对字符串进行排序。它可以很容易地适应您的情况:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void sortstrarr(void *array, unsigned n);
static int cmpr(const void *a, const void *b);

int main(void) {
char line[1024];
char *line_array[1024];
int i = 0;
int j = 0;

printf ("Enter one string per line (ctrl+d when done)\n");

while(fgets(line, 1024, stdin)) {

if (i < 1024)
line_array[i++] = strdup(line);
else
break;
}

printf ("\npassing strings to sortstrarr (using qsort)\n\n");

sortstrarr (line_array, i);

while (j < i)
printf ("%s", line_array[j++]);

return 0;
}

static int cmpr (const void *a, const void *b) {
return strcmp(*(char **)a, *(char **)b);
}

void sortstrarr (void *array, unsigned n) {
qsort (array, n, sizeof(char *), cmpr);
}

输出

Enter one string per line (ctrl+d when done)
this is my string
alother one
maybe one more
been there
done that

passing strings to sortstrarr (using qsort)

alother one
been there
done that
maybe one more
this is my string

关于c - 在 C 中对二维数组的行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24318402/

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