自然排序中的C - "字符串数组,包含数字和字母" [英] Natural sort in C - "array of strings, containing numbers and letters"
问题描述
寻找一个证明的工作算法进行生产。 没有看到这个例子 但没有找到多少人在网上或书。
Looking for a proven to work algorithm for production. Did see this example but not finding much else on the web or in books.
即。 file_10.txt> file_2.txt
i.e. file_10.txt > file_2.txt
感谢。
推荐答案
我假设你已经知道了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.
这篇关于自然排序中的C - &QUOT;字符串数组,包含数字和字母&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!