更新时间:2023-02-15 21:06:37
我假设你已经知道了C标准库的qsort()
功能:
I assume you already know the C standard library qsort()
function:
void qsort(void *base,
size_t nel,
size_t width,
int (*compar)(const void *, const void *);
这是最后一个参数是的函数指针的,这意味着你可以通过任何功能吧。你可以使用的strcmp()
,其实,但会给你ASCIIbetical,并且你特别希望有一个自然排序。
That last parameter is a function pointer, which means you can pass any function to it. You could use strcmp()
, in fact, but that would give you ASCIIbetical, and you specifically want a natural sort.
在这种情况下,你可以写一个pretty的轻松:
In that case, you could write one pretty easily:
#include <ctype.h>
int natural(const char *a, const char *b)
{
if(isalpha(*a) && isalpha(*b))
{
// compare two letters
}
else
{
if(isalpha(*a))
{
// compare a letter to a digit (or other non-letter)
}
else if(isalpha(*b))
{
// compare a digit/non-letter to a letter
}
else
{
// compare two digits/non-letters
}
}
}
部分的其他
取值可能被清除了,如果你只是返回
早,但有一个基本的结构。检查文件ctype.h
像功能因而isalpha()
(如果一个字符是字母的一部分), ISDIGIT()
, isspace为()
,等等。
Some of the else
s could be cleared up if you just return
early, but there's a basic structure. Check ctype.h
for functions like isalpha()
(if a character is part of the alphabet), isdigit()
, isspace()
, and more.