字符串分割strtok_s

1、strtok、strtok_s分割字符串

https://blog.csdn.net/hustfoxy/article/details/23473805/ 

https://www.cnblogs.com/luverose/p/4248992.html

https://www.cnblogs.com/happinessday/p/6381027.html

1)、strtok函数

函数原型:char * strtok (char *str, const char * delimiters);     

参数:str,待分割的字符串(c-string);delimiters,分割符字符串。

该函数用来将字符串分割成一个个片段。参数str指向欲分割的字符串,参数delimiters则为分割字符串中包含的所有字符。当strtok()在参数s的字符串中发现参数delimiters中包涵的分割字符时,则会将该字符改为 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针。
需要注意的是,使用该函数进行字符串分割时,会破坏被分解字符串的完整,调用前和调用后的s已经不一样了。第一次分割之后,原字符串str是分割完成之后的第一个字符串,剩余的字符串存储在一个静态变量中,因此多线程同时访问该静态变量时,则会出现错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
    char str[]="ab,cd,ef";
    char *ptr;
    printf("before strtok:  str=%s
",str);
    printf("begin:
");
    ptr = strtok(str, ",");
    while(ptr != NULL){
        printf("str=%s
",str);
        printf("ptr=%s
",ptr);
        ptr = strtok(NULL, ",");
    }
    system("pause");
    return 0;
View Code

2)、strtok_s函数
strtok_s是windows下的一个分割字符串安全函数,其函数原型如下:
char *strtok_s( char *strToken, const char *strDelimit, char **buf);
这个函数将剩余的字符串存储在buf变量中,而不是静态变量中,从而保证了安全性。

strtok_s(strToken, strDelimit, context,locale)

strToken

这个参数用来存放需要分割的字符或者字符串整体

strDelimit

这个参数用来存放分隔符(例如:,.!@#$%%^&*() 之类可以区别单词的符号)

context

这个参数用来存放被分割过的字符串

locale

这个参数用来储存使用的地址

在首次调用strtok_s这个功能时候会将开头的分隔符跳过然后返回一个指针指向strToken中的第一个单词,在这个单词后面茶插入一个NULL表示断开。多次调用可能会使这个函数出错,context这个指针一直会跟踪将会被读取的字符串。

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

char string[] = 
".A string	of ,,tokens
and some  more tokens"; 
char seps[] = " .,	
"; 
char *token = NULL; 
char *next_token = NULL;

int main(void) 
{ 
    printf("Tokens:
");

    // Establish string and get the first token: 
    token = strtok_s(string, seps, &next_token);

    // While there are tokens in "string1" or "string2" 
    while (token != NULL) 
    { 
        // Get next token: 
        if (token != NULL) 
        { 
            printf(" %s
", token); 
            token = strtok_s(NULL, seps, &next_token); 
        } 
    } 
    printf("the rest token1:
"); 
    printf("%d", token); 
}
View Code

 2、分割CString字符串

Left,Right,ReverseFind 

https://blog.csdn.net/rhddlr/article/details/76039299

https://blog.csdn.net/calmreason/article/details/73822565

说明:CStringArray只能用引用传入,不可以作为函数返回值,因为CStringArray集成的CObject不支持复制构造

 View Code

原文地址:https://www.cnblogs.com/wllwqdeai/p/10291629.html