C 进阶 — 字符函数和字符串函数 ( 二 )
C 进阶 — 字符函数和字符串函数 ( 二 )
书接上回 C 进阶 — 字符函数和字符串函数 ( 一 )
1.9 strtok
参考资料 strtok 函数用法详解
char * strtok ( char * str, const char * sep );
strtok
是 [C 标准库](https://so.csdn.net/so/search?q=C 标准库&spm=1001.2101.3001.7020)中的字符串分割函数,用于将一个字符串拆分成多个部分(token),以某些字符(称为分隔符)为界限
参数
- str:待分割的字符串。如果是第一次调用,传入要分割的字符串;之后的调用需传入
- NULL,以继续上一次的分割
- delim:字符串,包含所有分隔符的字符集合。例如," "(空格)或 “/”(斜杠)
返回值
- 返回指向字符串中 当前部分 的指针
- 如果没有更多部分可返回,返回 NULL
用法规则
- 初次调用时,传入字符串
str
,函数会从str
中找到第一个部分 - 函数会用
'\0'
替换找到的分隔符(破坏原字符串) - 后续调用时,传入
NULL
,函数会继续从上次结束的位置查找下一部分 - 不能在多线程环境中使用,因为
strtok
使用的是静态变量保存状态
/* strtok example */
#include <stdio.h>
#include <string.h>
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;
}/* 常规分割字符串 */
int main()
{char* p = "xxxxxxxxx@.mail.com";const char* sep = ".@";char arr[30];strcpy(arr, p); //将数据拷贝一份,处理 arr 数组内容char* str = strtok(arr, sep);for (; str != NULL; str = strtok(NULL, sep))printf("%s\n", str);return 0;
}
模拟 strtok 实现
static char* token_ptr = NULL;
char* my_strtok(char* str, const char* sep)
{assert(sep);if (str) token_ptr = str;if (!token_ptr) return NULL;/* 遍历分割数组 */const char* s = sep;const char* res = NULL;for (; *token_ptr; s = sep, ++token_ptr){/* 遍历分割符 */while (*s){if (*token_ptr != *s) /* 当前字符和分割符不相等 */{++s; //偏移比较下一个分割符//当前字符和分割符不相等, 且遍历完分割符时记录首元素if (!*s && !res) res = token_ptr;}else /* 当前字符和分割符相等 */{*token_ptr = 0;if (res) return ++token_ptr, res;break;}}}token_ptr = NULL;if (res) return res;
}
1.10 strerror
char * strerror ( int errnum );
获取指向错误消息字符串的指针Interprets the value of errnum, generating a string with a message that describes the error condition as if set to errno by a function of the library.
解释 errnum 的值,生成一个字符串,其中包含一条消息,该消息描述错误条件,就像由库的函数设置为 errno 一样The returned pointer points to a statically allocated string, which shall not be modified by the program. Further calls to this function may overwrite its content (particular library implementations are not required to avoid data races).
返回的指针指向静态分配的字符串,该程序不得修改该字符串。对此函数的进一步调用可能会覆盖其内容(不需要特定的库实现来避免数据竞争)The error strings produced by strerror may be specific to each system and library implementation.
生成的错误字符串 strerror 可能特定于每个系统和库实现
返回错误码,所对应的错误信息
/* strerror example : error list */
#include <stdio.h>
#include <string.h>
#include <errno.h>int main ()
{FILE * pFile;pFile = fopen ("unexist.ent","r");if (pFile == NULL)printf ("Error opening file unexist.ent: %s\n",strerror(errno)); //errno: Last error numberreturn 0;
}
字符分类函数
函数 如果他的参数符合下列条件就返回真
iscntrl 任何控制字符
isspace 空白字符:空格‘ ’,换页‘\f’,换行'\n',回车‘\r’,制表符'\t'或者垂直制表符'\v'
isdigit 十进制数字 0~9
isxdigit 十六进制数字,包括所有十进制数字,小写字母a~f,大写字母A~F
islower 小写字母a~z
isupper 大写字母A~Z
isalpha 字母a~z或A~Z
isalnum 字母或者数字,a~z,A~Z,0~9
ispunct 标点符号,任何不属于数字或者字母的图形字符(可打印)
isgraph 任何图形字符
isprint 任何可打印字符,包括图形字符和空白字符
字符转换
int tolower ( int c );
int toupper ( int c );/* isupper example */
#include <stdio.h>
#include <ctype.h>
int main ()
{int i=0;char str[]="Test String.\n";char c;while (str[i]){c = str[i];if (isupper(c)) c = tolower(c);putchar (c);i++;}return 0;
}
1.11 memcpy
void * memcpy ( void * destination, const void * source, size_t num );
- 函数 memcpy 从 source 的位置开始向后复制 num 个字节的数据到 destination 的内存位置
- 这个函数在遇到 \0 的时候并不会停下来
- 如果 source 和 destination 有任何的重叠,复制的结果都是未定义的
/* memcpy example */
#include <stdio.h>
#include <string.h>struct {char name[40];int age;
} person, person_copy;int main ()
{char myname[] = "Pierre de Fermat";/* using memcpy to copy string: */memcpy ( person.name, myname, strlen(myname)+1 );person.age = 46;/* using memcpy to copy structure: */memcpy ( &person_copy, &person, sizeof(person) );printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );return 0;
}
模拟 memcpy 实现
void* memcpy(void* destination, const void* source, size_t num)
{assert(destination && source);void* res = destination;while (num--)*((char*)destination)++ = *((char*)source)++;return res;
}
使用 memcpy 函数拷贝自身
src , src +3, 5
思考一下:对于数组:int arr[] = {1,2,3,4,5,6,7,8,9,10};
能否将1,2,3,4,5
拷贝到 3,4,5,6,7
的位置??从而结果为:1,2,1,2,3,4,5,8,9,10
呢 ?
答案是不能,下面是过程解析
由于在 memcpy 函数拷贝时,是按照字节来进行拷贝的,拷贝的数字将会覆盖原来的数字
1.12 memmove
void * memmove ( void * destination, const void * source, size_t num );
和 memcpy 的差别就是 memmove 函数处理的源内存块和目标内存块是可以重叠的(如果空间有重叠,则使用 memmove)
/* memmove example */
#include <stdio.h>
#include <string.h>
int main ()
{char str[] = "memmove can be very useful......";memmove (str+20,str+15,11);puts (str);return 0;
对于数组 arr1[]={1,2,3,4,5,6,7,8,9,10}
将 1,2,3,4,5
放到 3,4,5,6,7
的位置 ,可以用从后往前放的方法来实现。
第一步:将 5 放在 7 的位置,第二步:将 4 放在 6 的位置,第三步:将 3 放在 5 的位置 … 这样依次按照顺序来实现
将 4,5,6,7,8
放在 1,2,3,4,5
的位置,按照从后往前放的方式来进行思考的话:那么:第一步:将 8 放在 5 的位置,第二步:将 7 放在 4 的位置,第三步:将 6 放在 3 的位置,第四步:将 5 放在 …(注意此时 5 的位置处,放置的不再是 5了,已经被前面的 8 替代,所以显得非常不合理)
将 4,5,6,7,8
放在 1,2,3,4,5
的位置,则需要从前往后放来实现。第一步:将 4 放在 1 的位置,第二步:将 5 放在 2 的位置,第三步:将 6 放在 3 的位置 …
模拟 memmove 实现
void* memmove(void* destination, const void* source, size_t num)
{assert(destination && source);void* res = destination;/*内存重叠的情况源在前, 目标在后, 把前面部分拷贝内容到后面,需要从后往前放源在后, 目标在前, 把后面部分内容拷贝到前面,需要从前往后放*/if (destination < source) //比较地址{//从前往后放while (num--)*((char*)destination)++ = *((char*)source)++;}else{//从后往前放while (num--)*((char*)destination + num) = *((char*)destination + num);}return res;
}
1.13 memcmp
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
比较从 ptr1 和 ptr2 指针开始的 num 个字节;注意,与 strcmp 不同,该函数在找到 null 字符后不会停止比较
返回值
/* memcmp example */
#include <stdio.h>
#include <string.h>int main ()
{char buffer1[] = "DWgaOtP12df0";char buffer2[] = "DWGAOTP12DF0";int n;n=memcmp ( buffer1, buffer2, sizeof(buffer1) );if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);return 0;
}
模拟 memcmp 实现
int memcmp(const void* ptr1, const void* ptr2, size_t num)
{assert(ptr1 && ptr2);while (num--){if (*(char*)ptr1 != *(char*)ptr2) return *(char*)ptr1 - *(char*)ptr2;(char*)ptr1 += 1;(char*)ptr2 += 1;}return 0;
}
动手写代码前,必须先把逻辑理清楚,怎样算理清 ?就是能用汉字或画图准确的描述出自己当前的思路(可能不一定是对的),然后再按照描述把代码写出来(如果不正确则 DEBUG 排查)
假设已知当前的条件,递推出后面的情况,进行逻辑的整理,也是编程常用的思路手段(参考 KMP 的算法实现)