首页 > 代码库 > C练习之 输入一系列单词,以逗号分割,分行输出,删除头尾空格

C练习之 输入一系列单词,以逗号分割,分行输出,删除头尾空格

#define __STDC_WANT_LIB_EXT1__ 1            // Make optional versions of functions available
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX_LEN 5000

int main(void)
{    
    char list[MAX_LEN]; //stores the list of comma words
    const char comma[] = ","; //the only word delimiter
    
    printf("Enter a comma separated list of words:\n");

    gets_s(list ,sizeof(list));

    size_t index = 0;
    size_t i=0;
    do
    {
        if(isspace(list[i]))
            continue;
        list[index++] = list[i];//先执行list[index]=list[i],再执行index++
        i++;
    }while(list[i]!=\0);
    

    char *ptr = NULL;
    size_t list_len = strnlen_s(list,MAX_LEN);
    char *pWord = strtok_s(list,&list_len,comma,&ptr);
    if(pWord)
    {
        do
        {
            printf("%s\n",pWord);
            pWord = strtok_s(NULL,&list_len,comma,&ptr);
        }while(pWord);
        
    }
    return 0;
}

 

C练习之 输入一系列单词,以逗号分割,分行输出,删除头尾空格