特别要注意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;
}

猜你喜欢

转载自blog.csdn.net/chenhao0568/article/details/105268056