zoukankan      html  css  js  c++  java
  • strtok()的簡單使用範例

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

    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()。

  • 相关阅读:
    HDU 1874 畅通工程续(dijkstra)
    HDU 2112 HDU Today (map函数,dijkstra最短路径)
    HDU 2680 Choose the best route(dijkstra)
    HDU 2066 一个人的旅行(最短路径,dijkstra)
    关于测评机,编译器,我有些话想说
    测评机的优化问题 时间控制
    CF Round410 D. Mike and distribution
    数字三角形2 (取模)
    CF Round410 C. Mike and gcd problem
    CF Round 423 D. High Load 星图(最优最简构建)
  • 原文地址:https://www.cnblogs.com/lzjsky/p/1861728.html
Copyright © 2011-2022 走看看