字符串分割函数 strtok

1. 字符串分割函数strtok,其中一个用途是可以用来读取配置文件中的内容,程序启动时把相应参数进行初始化.

2.源程序

/* yang.txt 中内容为*/

/*wo shi shei?
   nSta = , 5 */

 FILE *fp;
 char strLine[513];
 char *ptr;
 CString str,tmpStr;

 char *token;
 char *seps = " ,///=/n";

 memset(strLine,0,sizeof(strLine));

 if( (fp = fopen("yang.txt","r") ) != NULL)
 {
  while( !feof(fp))
  {
   ptr = fgets(strLine,512,fp);
   if( ptr == NULL)
   {
    continue;
   }
   while( (*ptr == ' ') || (*ptr == '/t'))
    ptr++;
   if( *ptr == '#' || *ptr == 0 || *ptr == '/n')
    continue;

   token = strtok(ptr,seps);
   while( token != NULL)
   {
    tmpStr = token;
    str += tmpStr;
    str += "/n";

    token = strtok(NULL,seps);// 第二次调用时第一参数为NULL
   }

  }

  AfxMessageBox(str);

// str 为:

// wo

// shi

// shei?

// nSta

// 5

3.strtok函数说明: (from msdn)

1)char *strtok( char *strToken, const char *strDelimit );

2)Parameters

strToken: 包含tokens的字符串

strDelimit: 包含所有分隔符字符的字符串

3) function:

根据strDelimit中的字符来分割字符串 strToken,以下时msdn的描述:

The strtok function finds the next token in strToken. The set of characters in strDelimit specifies possible delimiters of the token to be found in strToken on the current call.

On the first call to strtok, the function skips leading delimiters and returns a pointer to the first token in strToken, terminating the token with a null character. More tokens can be broken out of the remainder of strToken by a series of calls to strtok. Each call to strtok modifies strToken by inserting a null character after the token returned by that call. To read the next token from strToken, call strtok with a NULL value for the strToken argument. The NULL strToken argument causes strtok to search for the next token in the modified strToken. The strDelimit argument can take any value from one call to the next so that the set of delimiters may vary.

4) 说明:

字符串不可再分时,即查找不到新的token时返回NULL;否则返回分隔符前的字符串指针.

第一次调用strok时,自动去除掉最前面的分隔符.

4  fgets函数

fgets(char * str,int nLen,FILE *fp);

从文件中读取nLen-1个字符到str中.

读取出错时返回NULL

遇到/n或读取到的字符串的个数为nLen-1个时,返回值为读取到的字符串的首地址,内容同str.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值