zoukankan      html  css  js  c++  java
  • C语言 字符串切割

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    /* 字符串切割函数 */
    
    /*
    知识补充:
        1. 函数原型:
        char *strtok(char *str, const char *delim);
        char *strsep(char **stringp, const char *delim);
    
        2. 功能: 
        strtok和strsep两个函数的功能都是用来分解字符串为一组字符串。str为要分解的字符串,delim为分隔符字符串。
    
        3. 参数说明:
        str(stringp)要求不可以是 const char *,因为 strtok 或者 strsep 都会修改 str 的值(修改指针的值)
        delim 可以多个字符的集合,strtok(strsep)会按单个字符切割子串
    
        4. 返回值:
        从str开头开始的第一个子串,当没有分割的子串时返回NULL。
    
        5. 相同点:
        两者都会改变源字符串,想要避免,可以使用strdupa(由allocate函数实现)或strdup(由malloc函数实现)。
    
        6. 不同点:
        a. strtok函数第一次调用时会把s字符串中所有在delim中出现的字符替换为NULL。然后通过依次调用strtok(NULL, delim)得到各部分子串。
        b. strsep函数第一次调用时会把s字符串中所有在delim中出现的字符替换为''。然后通过依次调用strtok(stringp, delim)得到各部分子串。
        c. strsep在切割字符串的过程中,可能多次返回空字符串(''),但是 strtok 只会在结束时才返回 NULL
        d. strtok 内部记录上次调用字符串的位置,所以不支持多线程,可重入版本为strtok_r
        e. strsep支持多线程
    
    */
    
    void test()
    {
        char p[] = "hello this world . the world is good .";
        char *pcIndex = p;
        char *token = NULL;
    
        while (token = strsep(&buf, ". "), token)
        {
            //*token 可能会等于 ''
            if (*token)
            {
                printf("--[%s]---[%p]---buf[%p]--
    ", token, token, buf);
            }
        }
    
    }
    
    int main()
    {
        test();
        return 0;
    }
  • 相关阅读:
    *** 实现冒泡排序模板
    *** 实现stack模板
    python uses xml
    [转]给未来的电子通信工程师
    *** strRevert.cpp
    *** strlen.cpp
    *** checkRevStr.cpp 查看字符串是否是回文
    *** 自己代码:实现字符串比较
    *** 自写代码:查找两个字符串的最大公共子串
    *** 自写代码:在字符串中插入连续字符的个数
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/11605149.html
Copyright © 2011-2022 走看看