|
发表于 2022-4-1 17:20:31
|
显示全部楼层
按照题目要求,这道题并没那么简单。需要用到动态分配内存。
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define BUF 1024
- /*
- 从字符串str中获取以空格分割的第1个单词,然后修改指针指向下一个单词,直到'\0'为止,最后置*str==NULL。
- 参数:
- str 以'\0'结束的字符串。
- 返回值:
- 成功 返回单词所在的内存指针。
- 失败 返回NULL。
- */
- char *getWord(char **str)
- {
- char *buf=NULL, c;
- int i, len;
- if(*str==NULL)
- {
- return NULL;
- }
- // 判断字符串长度为0返回
- len = strlen(*str);
- if(len==0)
- {
- return NULL;
- }
- // 删除字符串前面的所有空格
- for(i=0; i<=len; i++)
- {
- if((*str)[i]!=' ')
- {
- break;
- }
- }
- *str += i;
- // 再次判断字符串长度为0返回(到了尾部的空格处理)
- len = strlen(*str);
- if(len==0)
- {
- return NULL;
- }
- // 为单词分配内存
- buf = (char*)malloc(sizeof(char)*BUF);
- if(buf==NULL)
- {
- printf("内存分配失败。-3");
- return NULL;
- }
- // 获取单词
- for(i=0; i<=len; i++)
- {
- c = (*str)[i];
- if(c==' ' || c=='\0')
- {
- buf[i] = '\0';
- break;
- }
- buf[i] = c;
- }
- if(c=='\0')
- {
- *str = NULL;
- }
- else
- {
- *str = *str+i*sizeof(char);
- }
- return buf;
- }
- /*
- 从用户输入的字符串获取以空格分割的个单词。
- 参数:
- *words[] 存储单词的指针数组。
- len *words指针数组的总长度。
- 返回值:
- 返回所有单词的个数。
- */
- int getWords(char *words[], int len)
- {
- char *str=NULL, *str_temp=NULL;
- char *buff=NULL;
- int i;
- // 获取字符串
- str = (char *)malloc(sizeof(char)*BUF);
- if(str==NULL)
- {
- printf("内存分配失败-1。");
- return 0;
- }
- i=1;
- while(gets(str)==NULL)
- {
- str = (char *)realloc(str, sizeof(char)*BUF*(++i));
- if(str==NULL)
- {
- printf("内存分配失败-2。");
- return 0;
- }
- }
- str_temp = str;
- i=0;
- while( (buff=getWord(&str_temp)) != NULL )
- {
- words[i] = buff;
- i++;
- }
- free(str);
- str=NULL;
- return i;
- }
- /*
- 释放 *words[]指针数组中元素的内存
- */
- void freeWords(char *words[])
- {
- char *buf;
- while( (buf=*words++)!=NULL )
- {
- free(buf);
- }
- }
- /*
- 统计单词的个数。
- 参数:
- *words[] 存储单词的指针数组。
- *word 目标单词。
- 返回值:
- 返回匹配到的数量。
- */
- int countWord(char *words[], char *word)
- {
- char *buf;
- int count = 0;
- while( (buf=*words++)!=NULL)
- {
- if(!strcmp(buf, word)) ++count;
- }
- return count;
- }
- int main(void) {
- char *words[100100]={NULL}; // 最多保存100100个字符串
- char word[BUF]={'\0'};
- int len = 0, count;
- len = getWords(words, 100100);
- printf("请输入要统计的单词(区分大小写):");
- scanf("%s", &word);
- count = countWord(words, word);
- printf("%d\n", count);
- freeWords(words);
- return 0;
- }
复制代码 |
评分
-
查看全部评分
|