Logo Search packages:      
Sourcecode: bglibs version File versions

int str_sort ( str s,
char  sep,
long  count,
int(*)(const str_sortentry *a, const str_sortentry *b)  fn 
)

Sort a string.

Parameters:
s The string to sort.
sep The character which delimits the substrings.
count The number of substrings within s (set to -1 if not known).
fn The comparison function. Defaults to a function that works like memcmp.
Note:
This function allocates a temporary array of substring pointers, and so may return 0 if memory allocation fails. The string itself is not reallocated.

Definition at line 51 of file sort.c.

References len, s, str_catb(), str_catc(), str_copy(), str_free(), and str_truncate().

{
  str_sortentry* ptrs;
  const char* ptr;
  const char* end;
  long i;
  str tmp = {0,0,0};
  if (count == -1) {
    for (count = 0, ptr = s->s, end = s->s+s->len; ptr != 0 && ptr < end;
       ++count) {
      ptr = memchr(ptr, sep, end-ptr);
      if (ptr) ++ptr;
    }
  }
  if ((ptrs = alloca(count * sizeof *ptrs)) == 0) return 0;
  if (!str_copy(&tmp, s)) { str_free(&tmp); return 0; }
  if (fn == 0) fn = default_cmp;
  for (i = 0, ptr = tmp.s, end = tmp.s+tmp.len; i < count; ++i) {
    const char* ptrend = memchr(ptr, sep, end-ptr);
    if (ptrend == 0) ptrend = end;
    ptrs[i].str = ptr;
    ptrs[i].len = ptrend - ptr;
    ptr = ptrend + 1;
  }
  qsort(ptrs, count, sizeof(*ptrs), (int (*)(const void*,const void*))fn);
  str_truncate(s, 0);
  for (i = 0; i < count; i++) {
    str_catb(s, ptrs[i].str, ptrs[i].len);
    str_catc(s, sep);
  }
  str_free(&tmp);
  return 1;
}


Generated by  Doxygen 1.6.0   Back to index