gpt4 book ai didi

c - 如何按字典顺序对结构中的字符串进行排序?

转载 作者:行者123 更新时间:2023-12-02 01:16:41 25 4
gpt4 key购买 nike

我正在尝试根据名称字典顺序对字符串进行排序。

所以我有一个结构数组

typedef struct buff{
char *name;
} structure;

我正在复制文件名及其关联的扩展名。因此该结构的内容看起来像 s[0].name = "picture1.jpg" s[1].name = "DCP003.JPG" 之类的东西那个。

我正在努力解决这个问题,但我无法做到这一点..我目前所拥有的是这个。

void sort(structure *s, int counter){

for (int i = 0; i < counter - 1; i++){
for (int j = 0; j < counter - 1 - i; j++){

if (strcmp(s[j].name, s[j+1].name) > 0){

structure tmp;

tmp = s[j];
s[j] = s[j+1];
s[j+1] = tmp;

}
}
}

for (int i = 0; i < counter; i++){
printf("%d - %s\n", i+1, s[i].name);
}
}

它并没有像我想要的那样工作.. 尝试了几个版本仍然没有用.. 我哪里出错了?非常感谢任何建议..

最佳答案

按字典顺序对结构中的字符串进行排序的最佳方法是使用 QSort (Stdlib.h)(O(nlog(n)))。

这是示例代码::

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


struct names
{
char strvalues[20];
} buff[100];


int main ()
{
int i;
strcpy(buff[0].strvalues,"some");
strcpy(buff[1].strvalues,"example");
strcpy(buff[2].strvalues,"strings");
strcpy(buff[3].strvalues,"here");

qsort (buff, 4, 20, (int(*)(const void*,const void*)) strcmp);


for(i=0;i<4;++i)
{
printf("%s\n",buff[i].strvalues);
}

return 0;
}

关于c - 如何按字典顺序对结构中的字符串进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10557862/

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