2015年1月3日 星期六

C 字符串分割

函数名: strtok
功  能: 查找由在第二个串中指定的分界符分隔开的单词
用  法: char *strtok(char *str1, char *str2);
程序例:

#include <string.h>
#include <stdio.h>

int main(void)
{
   char input[16] = "abc,d";
   char *p;

   /* strtok places a NULL terminator
   in front of the token, if found */
   p = strtok(input, ",");
   if (p)   printf("%s\n", p);

   /* A second call to strtok using a NULL
   as the first parameter returns a pointer
   to the character following the token  */
   p = strtok(NULL, ",");
   if (p)   printf("%s\n", p);
   return 0;
}
這個程式的輸出如下所示:
下列是程式的上述在執行期間中語彙基元的指標周圍的記憶體區域的範例表示。請注意取代以 NULL 字元分隔符號的語彙基元位於每個時間:
   -------------------------------------------------------------
   |a |  |s |t |r |i |n |g |, |o |f |  |, |, |t |o |k |e |n |s |
   -------------------------------------------------------------
   This is the original string before the first call to strtok().


   -------------------------------------------------------------
   |a |\0|s |t |r |i |n |g |, |o |f |  |, |, |t |o |k |e |n |s |
   -------------------------------------------------------------
    ^----- Token will point here on the first call.

   -------------------------------------------------------------
   |a |\0|s |t |r |i |n |g |\0|o |f |  |, |, |t |o |k |e |n |s |
   -------------------------------------------------------------
          ^------ Token will point here on the second call.

   -------------------------------------------------------------
   |a |\0|s |t |r |i |n |g |\0|o |f |\0|, |, |t |o |k |e |n |s |
   -------------------------------------------------------------
                               ^----- Token will point here on
                                      the third call.

                                (and so on)
    

沒有留言:

張貼留言