分类: C/C++
2011-03-02 21:10:06
所有C语言标准库支持的字符串操作都在string.h中,这个文件在/usr/include/下。确切的说,这个文件还包含对数组的访问。所包含的函数分为以下几类:复制、连接、比较、查找等。
void * memcpy ( void * destination, const void * source, size_t num );
void * memmove ( void * destination, const void * source, size_t num );
char * strcpy ( char * destination, const char * source );
char * strncpy ( char * destination, const char * source, size_t num );
char * strcat ( char * destination, const char * source );
char * strncat ( char * destination, char * source, size_t num );
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
int strcmp ( const char * str1, const char * str2 );
int strcoll ( const char * str1, const char * str2 );
int strncmp ( const char * str1, const char * str2, size_t num );
size_t strxfrm ( char * destination, const char * source, size_t num );
const void * memchr ( const void * ptr, int value, size_t num );
const char * strchr ( const char * str, int character );
size_t strcspn ( const char * str1, const char * str2 );
const char * strpbrk ( const char * str1, const char * str2 );
const char * strrchr ( const char * str, int character );
size_t strspn ( const char * str1, const char * str2 );
const char * strstr ( const char * str1, const char * str2 );
char * strtok ( char * str, const char * delimiters );
/* strtok example */
#include
#include
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
void * memset ( void * ptr, int value, size_t num );
char * strerror ( int errnum );
size_t strlen ( const char * str );
函数strtok很有趣,通过上面的例子可以看到这个函数自身会记录一些变量信息,供下次被调用时使用。记录在哪里?怎么就记录了呢?下面是在glibc中strtok最简单的实现方式.原来只是个全局变量而已:) 有意思。
static char *olds;
/* Parse S into tokens separated by characters in DELIM.
If S is NULL, the last string strtok() was called with is
used. For example:
char s[] = "-abc-=-def";
x = strtok(s, "-"); // x = "abc"
x = strtok(NULL, "-="); // x = "def"
x = strtok(NULL, "="); // x = NULL
// s = "abc\0=-def\0"
*/
char *
strtok (s, delim)
char *s;
const char *delim;
{
char *token;
if (s == NULL)
s = olds;
/* Scan leading delimiters. */
s += strspn (s, delim);
if (*s == '\0')
{
olds = s;
return NULL;
}
/* Find the end of the token. */
token = s;
s = strpbrk (token, delim);
if (s == NULL)
/* This token finishes the string. */
olds = __rawmemchr (token, '\0');
else
{
/* Terminate the token and make OLDS point past it. */
*s = '\0';
olds = s + 1;
}
return token;
}
chinaunix网友2011-03-06 09:16:27
很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com