特別要注意strtok分割處理後原字符串str會變,變成第一個子字符串。求動態字符串長度不能用sizeof,可以使用strlen()+1

#include <string.h>
#include <stdio.h>
 
int main () {
   char str[80] = "This is - www.wjsou.com - website";
   const char s[2] = "-";
   char *token;
   
   /* 獲取第一個子字符串 */
   token = strtok(str, s);
   
   /* 繼續獲取其他的子字符串 */
   while( token != NULL ) {
      printf( "%s\n", token );
    
      token = strtok(NULL, s);
   }
   printf("\n%s\n",str);
   return(0);
}

輸出

This is 
 www.wjsou.com 
 website

This is 

 

 

改進1成字符串分割函數

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int splitString(char dst[][50], char *str, const char *spl)
{
    char *str_copy = calloc(1, strlen(str)); //分配1個str大小的空間,分配空間後會清0
    strcpy(str_copy, str);                   //防止分割處理後原字符串改變

    int n = 0;
    char *result = NULL;
    result = strtok(str_copy, spl);
    while (result != NULL)
    {
        strcpy(dst[n++], result);
        result = strtok(NULL, spl);
    }
    free(str_copy);
    return n;
}

int main()
{
    while (1)
    {
        char str[100] = "1,0";
        char result[20][50] = {{0}};
        int size = splitString(result, str, ",");
        printf("\n%d\n", size);
        printf("\n%s\n", str);
        int i = 0;
        for (; i < size; i++)
            printf("\n%s\n", result[i]);

        printf("\n----------------------------------\n");
    }

    return (0);
}

2最終版:不使用分配內存等高級的操作。

int splitString(char dst[][50], char *str, const char *spl)
{
    char str_copy[strlen(str)+1];
    strcpy(str_copy, str);                   //使用備份,防止分割處理後原字符串改變

    int n = 0;
    char *result = NULL;
    result = strtok(str_copy, spl);
    while (result != NULL)
    {
        strcpy(dst[n++], result);
        result = strtok(NULL, spl);
    }
    return n;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章