有一段文本,将文本中的所有单词,存放到一个字符指针数组中(要求每个单词内存恰好)

来源:互联网 发布:groovy mac 编辑:程序博客网 时间:2024/06/02 21:29

    char a[] ="  my    name is hanmeimei lilei and you no fine thanks  ";

   int i = 0;//循环变量

    int j =0;//记录每个单词的长度

    int k =0;//记录指针数组的下标

   char *words[100] = {0};//定义一个指针数组,存放堆区空间地址

   char tempStr[20] = {0};//定义一个临时字符数组,存储单词

   while (1) {

       if (a[i] != ' ' && a[i] !='\0') {

            tempStr[j] = a[i];//a[i]没有遇到空格和'\0',a[i]中的字符拷贝到临时字符数组中

            j++;

        }else if(j !=0){

            tempStr[j] = '\0';//a[i]遇到' '或者'\0',在临时字符数组中补上'\0'

            words[k] =malloc(strlen(tempStr) +1);//在堆区开辟当前字符串所需的空间

           strcpy(words[k], tempStr);//将临时数组中的内容拷贝到堆区中

            k++;

            j =0;

        }

        

       if (a[i] == '\0') {

            break;//a[i] == 0,跳出循环

        }

        i++;

    }

   for (int n =0; n < k; n++) {

       printf("%s ", words[n]);

       free(words[n]);//释放空间

        words[n] =NULL;//指针指向无效空间

    }


0 0
原创粉丝点击