李sir_Blog

博客园 首页 联系 订阅 管理
  705 随笔 :: 58 文章 :: 134 评论 :: 193万 阅读

發現一個很好的台灣的博客。可以當作書來閱讀

http://www.cnblogs.com/oomusou/archive/2009/05/10/c_strtok.html

Abstract
strtok()的簡單使用範例。

Introduction
使用環境 : Visual Studio 2008

strtok.c / C

复制代码
1 /* 
2 (C) OOMusou 2009 http://oomusou.cnblogs.com
3 
4 Filename    : strtok.c
5 Compiler    : Visual C++ 9.0
6 Description : Demo how to use strtok() in C
7 Release     : 05/09/2009 1.0
8 */
9 #include <stdio.h>
10 #include <string.h>
11 
12 int main() {
13   char str[] = "Hello,World";
14   const char *del = ",";
15   char *s = strtok(str, del);
16 
17   while(s != NULL) {
18     printf("%s\n", s);
19     s = strtok(NULL, del);
20   }
21 
22   return 0;
23 }
复制代码


執行結果

strtok

完整程式碼下載
strtok.7z

Remark
csie-tw問到,為什麼第二次呼叫時,要使用strtok(NULL, del),這是一個很好的問題,所謂『有code有真相』,來看看Microsoft怎麼實作strtok()。

https://research.microsoft.com/en-us/um/redmond/projects/invisible/src/crt/strtok.c.htm

复制代码
1 /* Copyright (c) Microsoft Corporation. All rights reserved. */
2 
3 #include <string.h>
4 
5 /* ISO/IEC 9899 7.11.5.8 strtok. DEPRECATED.
6  * Split string into tokens, and return one at a time while retaining state
7  * internally.
8  *
9  * WARNING: Only one set of state is held and this means that the
10  * WARNING: function is not thread-safe nor safe for multiple uses within
11  * WARNING: one thread.
12  *
13  * NOTE: No library may call this function.
14  */
15 
16 char * __cdecl strtok(char *s1, const char *delimit)
17 {
18     static char *lastToken = NULL; /* UNSAFE SHARED STATE! */
19     char *tmp;
20 
21     /* Skip leading delimiters if new string. */
22     if ( s1 == NULL ) {
23         s1 = lastToken;
24         if (s1 == NULL)         /* End of story? */
25             return NULL;
26     } else {
27         s1 += strspn(s1, delimit);
28     }
29 
30     /* Find end of segment */
31     tmp = strpbrk(s1, delimit);
32     if (tmp) {
33         /* Found another delimiter, split string and save state. */
34         *tmp = '\0';
35         lastToken = tmp + 1;
36     } else {
37         /* Last segment, remember that. */
38         lastToken = NULL;
39     }
40 
41     return s1;
42 }
复制代码


可以發現,當S1為NULL時,他會使用lastToken這個static char *這個pointer+1繼續搜尋,若S1 != NULL,則當成第一次使用strtok()。

posted on   李sir  阅读(680)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示