• 字符串分割SplitString


    C/C++中常用的字符串切割函数有strtok、strtok_s与strtok_r。

    strtok函数

    char* strtok(char* str, const char* delim);
    

    分解字符串str为一组字符串,delim为分隔符。当strtok在參数str的字符串中发现參数delim中包含的切割字符时,则会将该字符改为''字符。在第一次调用时,strtok必需给予參数str字符串,往后的调用则将參数str设置成NULL。每次调用成功则返回指向被切割出片段的指针。

    strtok_s函数

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

    strtok_s是windows下的一个切割字符串安全函数,该函数会将剩余的字符串存储在buf变量中,而不是静态变量中,从而保证了安全性。

    strtok_r函数

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

    strtok_r函数是linux下切割字符串的安全函数,该函数会破坏待分解字符串的完整性,可使其将剩余的字符串保存在saveptr变量中,保证了安全性。

    SplitString实现

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    void SplitString (char* str, char* delim, char** result) {
        char* ptr = NULL;
        char* tmp = NULL;
        
        ptr = strtok_r(str, delim, &tmp);
        
        int count = 0;
        const int maxLineLen = 100;
        
        while (ptr != NULL) {
            memcpy(result[count], ptr, maxLineLen);
            ptr = strtok_r(NULL, delim, &tmp);
            ++count;
        }
    }
    
    void SplitStringTest () {
        
        const int maxLineNum = 20;
        const int maxLineLen = 100;
        
        char str1[] = "This is a test Program!";
        // char str1[] = "Indulge not in heedlessness, have no intimacy with sensuous delights; for the earnest, meditative person obtains abundant bliss.";
        char str2[] = " ";
        char* result[maxLineNum] = {0};
        
        for (int i = 0; i < maxLineNum; ++i) {
            result[i] = (char*)malloc(sizeof(char) * maxLineLen);
            
            if (result[i] != NULL) {
                memset(result[i], 0, maxLineLen);
            } else {
                return;
            }
        }
        
        SplitString(str1, str2, result);
        
        for (int i = 0; i < maxLineNum; ++i) {
            printf("%s
    ", result[i]);
        }
        
        for (int i = 0; i < maxLineNum; ++i) {
            if (result[i] != NULL) {
                free(result[i]);
                result[i] = NULL;
            }
        }
    }
    
    int main () {
        SplitStringTest();
        
        return 0;
    }
    

    个人主页:

    www.codeapes.cn

  • 相关阅读:
    Ubuntu 忘记root密码的解决方法
    zabbix 参数说明
    Python 进阶_OOP 面向对象编程_self 的实例绑定
    centos 6.5关闭NetworkManager
    本地yum源
    VMware通过VMnet8共享本地网络
    EasyUI之手风琴Accordion
    php 分页
    修改css
    /Home/Tpl/Equipment/rangeIndex.html 里调用魔板
  • 原文地址:https://www.cnblogs.com/codeapes666/p/12089156.html
Copyright © 2020-2023  润新知