[Libclc-developers] new string functions: clc_str{n}{case}comm()
Status: Planning
Brought to you by:
augestad
|
From: Hallvard B F. <h.b...@us...> - 2003-03-23 14:33:14
|
> I think you should post the nice functions as well. Never know if
> someone needs them or suddenly finds a new way of doing things. :-)
OK, here are the clc_str{n}{case}comm() functions. Does anyone need
them? I don't:-)
NAME
clc_strcomm, clc_strncomm, clc_strcasecomm, clc_strncasecomm
- find common prefix of strings
SYNOPSIS
#include <clc_string.h>
long clc_strcomm(const char *s1, const char *s2);
long clc_strncomm(const char *s1, const char *s2, long len);
long clc_strcasecomm(const char *s1, const char *s2);
long clc_strncasecomm(const char *s1, const char *s2, long len);
DESCRIPTION
These functions find the length of the common prefix of two strings.
clc_strcomm() and clc_strncomm() do case-sensitive compare,
clc_strcasecomm() and clc_strncasecomm() case-insensitive.
clc_strcomm() and clc_strcasecomm() compare until the terminating
null characters. clc_strncomm() and clc_strncasecomm() also stop
after len characters compared equal.
If the strings are longer than LONG_MAX, the behaviors of
clc_strncomm() and clc_strncasecomm() are undefined.
RETURN VALUES
The functions return the common length of the strings, or -1 if the
strings compare equal.
CAVEATS
Note that the functions treat the size as long, not size_t.
SEE ALSO
clc(3), strcmp(3), strncmp(3), clc_strcasecmp(3), clc_strncasecmp(3)
Implementation choices:
- I used long instead of size_t as a length parameter to emphasize that
a long length is returned.
- I could have returned an error condition (-2?) from clc_str{case}cmp
if the strings were equal for more than LONG_MAX characters, but
didn't bother. I can't imagine these functions being used on other
than fairly short strings.
Source code for clc_strncasecomm() follows. The others are for the time
being left as an exercise for the reader.
/* $Id$ */
/*
* Copyright(c) 2003 Hallvard B Furuseth <h.b...@us...>
*/
#include <ctype.h>
#include <clc_assert.h>
#include <clc_string.h>
long
clc_strncasecomm(const char *s1, const char *s2, long len)
{
const char *start = s1;
clc_assert_arg(clc_strncasecomm, s1 != NULL && s2 != NULL);
for (; --len >= 0; ++s1, ++s2) {
if (tolower((unsigned char)*s1) != tolower((unsigned char)*s2))
return s1 - start;
if (*s1 == '\0')
break;
}
return -1;
}
#ifdef CLC_TEST
#include <stdio.h>
int
main()
{
if(clc_strncasecomm("abc", "ABD", 3) != 2 ||
clc_strncasecomm("abc", "ABD", 2) != -1 ||
clc_strncasecomm("abc", "ABD", 1) != -1 ||
clc_strncasecomm("ab", "ABD", 3) != 2 ||
clc_strncasecomm("abc", "DEF", 3) != 0 ) {
puts("Sorry.");
return 1;
}
return 0;
}
#endif /* CLC_TEST */
--
Hallvard
|