华为2013年9月技术面面试题(二)

题2:统计字符串中各个单词出现的次数,最多100个英文单词。如:"I am am aa bb cc bb aa",则I:1,am:2,aa:2,bb:2,cc:1

方法一:

#include <stdlib.h>
#include <stdio.h>
#include<string.h>


void Count_Word(char* buf);

int main()
{
  char* word="I am am aa bb cc bb aa";
  
  Count_Word(word);
  return 0;
}

void Count_Word(char* buf)
{    
    int m=0;
    if(buf==NULL)
        printf("ERROR");
    char* tmp=NULL;
    char* words[100];           //指针数组:数组里存放的是指针,指针指向字符串
    int count[100];
    memset(words,0,100);        //void *memset(void *s, char ch, size_t n);将s中前n个字节用字符ch替换并返回s 
    for(int n=0;n<100;n++)
        count[n]=0;
    tmp=buf;
    while(*buf!='')
    {    
        while(*buf!=' '&&*buf!='')
            buf++;
        if(*buf==' '||*buf=='')
        {
            int len=buf-tmp;
            char* str=(char*)malloc(len+1);
            strncpy(str,tmp,len);
            *(str+len+1)='';
            for(int i=0;i<m;i++)
            {
                if(words[i]!=NULL&&strcmp(words[i],str)==0)//extern int strcmp(const char *s1,const char * s2);当s1<s2时,返回值= -1;=,返回0;否则返回1;
                {
                    count[i]++;
                    break;
                }
            }
            if(i==m)
            {
                words[m]=str;
                count[m]++;
                m++;    
            }    
            tmp=++buf;

        }
            
    }
    for(int k=0;k<100&&words[k]!=NULL;k++)
    {
       printf("word[%d] is:%s
",k,words[k]);
       printf("count[%d] is:%d
",k,count[k]);
    } 
}

 方法二:利用函数strchr(),//extern char *strchr(const char *s,char c);返回字符c第一次出现的地址,否则返回NULL

void Count_Word(char* buf)
{    
    int m=0;
    if(buf==NULL)
        printf("ERROR");
    char* tmp=NULL;
    char* words[100];           //指针数组:数组里存放的是指针,指针指向字符串
    int count[100];
    memset(words,0,100);        //void *memset(void *s, char ch, size_t n);将s中前n个字节用字符ch替换并返回s 
    for(int n=0;n<100;n++)
        count[n]=0;
    tmp=buf;
    while(*buf!='')
    {    
        char* end=buf;
        buf=strchr(buf,' ');    
        if(buf==NULL)
        { 
            buf=end;
            while(*buf!='')
                    buf++;
        }
        int len=buf-tmp;
        char* str=(char*)malloc(len+1);
        strncpy(str,tmp,len);
        *(str+len+1)='';
        for(int i=0;i<m;i++)
        {
            if(words[i]!=NULL&&strcmp(words[i],str)==0)
            {
                count[i]++;
                break;
            }
        }
        if(i==m)
        {
            words[m]=str;
            count[m]++;
            m++;
        }
        tmp=++buf;
    }
    for(int k=0;k<100&&words[k]!=NULL;k++)
    {
       printf("word[%d] is:%s
",k,words[k]);
       printf("count[%d] is:%d
",k,count[k]);
    } 
    
}
原文地址:https://www.cnblogs.com/fuxianfeng1988/p/3291226.html