打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C++ strtok函数详解

文章目录


strtok函数的作用是把字符串以规定的字符分割开:

头文件

#include <string.h>

函数原型

char *strtok(char s[], const char *delim);

参数

  • str – 要被分解成一组小字符串的字符串。
  • delim – 包含分隔符的 C 字符串。

返回值

该函数返回被分解的第一个子字符串,如果没有可检索的字符串,则返回一个空指针。

注意:

  1. 分割处理后原字符串 str 会变,变成第一个子字符串

  2. strtok函数会把分割前的字符串破坏掉,即每次分割后,原来的字符串就会少掉一部分,完整性会被破坏。

    例如:第一次分割之后,原字符串str是分割完成之后的第一个字符串,剩余的字符串存储在一个静态变量中,因此多线程同时访问该静态变量时,则会出现错误

使用案例

strtok函数会破坏被分解字符串的完整,调用前和调用后的s已经不一样了。如果要保持原字符串的完整,可以使用strchr和sscanf的组合等。

#include <string.h>
#include <stdio.h>
 
int main () {
   char str[80] = "this is - CSDN - blog";
   const char s[2] = "-";
   char *token;
   
   /* 获取第一个子字符串 */
   token = strtok(str, s);
   
   /* 继续获取其他的子字符串 */
   while( token != NULL ) {
      printf( "%s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}

输出

this is 
 CSDN 
  blog

拓展strtok_s与strtok_r

strtok_s函数

strtok_s是windows下的一个分割字符串安全函数,其函数原型如下:

char *strtok_s( char *strToken, const char *strDelimit, char **buf);

这个函数将剩余的字符串存储在buf变量中,而不是静态变量中,从而保证了安全性。

strtok_r函数

strtok_s函数是linux下分割字符串的安全函数,函数声明如下:

char *strtok_r(char *str, const char *delim, char **saveptr);

该函数也会破坏待分解字符串的完整性,但是其将剩余的字符串保存在saveptr变量中,保证了安全性。

拓展用例:

linux C:

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
int main()  
{  
    char str[]="ab,cd,ef";  
    char *ptr;  
    char *p;  
    printf("before strtok: str=%s\n",str);  
    printf("begin:\n");  
    ptr = strtok_r(str, ",", &p);  
    while(ptr != NULL){  
    // 输出时候 str都是 ab  也会被切割  破坏待分解字符串的完整性
        printf("str=%s\n",str);  
        printf("ptr=%s\n",ptr);  
        ptr = strtok_r(NULL, ",", &p);  
    }  
    return 0;  
}

输入结果:

before strtok: str=ab,cd,ef 
begin: 
str=ab 
ptr=ab 
str=ab 
ptr=cd 
str=ab 
ptr=ef
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C和指针之字符串strtok函数
Linux项目实战系列之:GPS数据解析
字符串函数
一文讲解C语言字符串
字符串与字符数组
C语言 字符串常用函数 示例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服