易百教程

编写程序以逗号分隔的单词列表

编写一个程序来分析以逗号分隔的单词列表。

从句子中提取单词并将其输出到一行,删除任何前导或尾随空格。

例如,如果输入是:

test,a,test

处理后输出将是:

test
a
test

实现代码

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX_LEN  5000                                      // Maximum string length
int main(void)
{
  char list[MAX_LEN] = "this  ,  is,  a,,  test";   // Stores the list of comma separated words
  const char comma[] = ",";  // 单词唯一分隔符

   // 删除空格
  size_t index = 0;    // 字符位置
  size_t i = 0;/*from www . j a va2 s  .co  m*/
  do
  {
    if (isspace(list[i]))                            // If it's whitespace...
      continue;                                     // ... skip the character...
    list[index++] = list[i];                        // ... otherwise copy the character
  } while (list[i++] != '\0');

  // Find words in list
  char *ptr = NULL;
  size_t list_len = strnlen_s(list, MAX_LEN);
  char *pWord = strtok_s(list, comma, &ptr);    // Find 1st word
  if (pWord)
  {
    do
    {
      printf("%s\n", pWord);
      pWord = strtok_s(NULL, comma, &ptr);      // Find subsequent words
    } while (pWord);   // NULL ends tokenizing
  }

  return 0;
}