c 代码存档: 快速查找相同的元素(数组版)

#include <stdio.h>

#define BUFSIZE 21
typedef enum {false=0,true=1} Boolean;

int GetString(char *buf)
{
     int ch;
     int i=0;
     while( (ch=getchar())!=EOF && ch!='/n')
          {
                 if (i==BUFSIZE-1)
                  {
                       printf("Are you trying to overflow the buffer? size=%d/n",BUFSIZE-1);
                       while( (ch=getchar())!=EOF && ch!='/n' ){;}
                       break;
                  }
               buf[i++]=ch;
          }
     buf[i]='/0';
     if (i==0)
          {
               printf("You've entered nothing!/n");
               //exit(1);
          }
     return i;

}
int GetInput(char *buf)
{
     int stringSize;
    
     //Give user a chance to re-enter the input when they failed for the first time
     do {
          printf("Please enter a string(less than %d chars)/n",BUFSIZE-1);
          stringSize = GetString(buf);
          //printf("stringSize = %d/n",stringSize);
         
     }while(stringSize==0);
    
     return stringSize;
    
}
   
void reportSame(char *buf,int stringSize)
{
     int count;
     int i,j;
     for (i=0;i<stringSize;++i)
          {
               if(buf[i]=='/0')
                    continue;
                    
               count=1;
               for (j=i+1;j<stringSize;++j)
                    {
                         if(buf[i]==buf[j])
                              {
                                   ++count;
                                   buf[j]='/0';
                              }
                    }
               printf("There are %d '%c's in the string/n",count,buf[i]);
          }
}


int main (int argc, int **argv)
{
     char inputBuf[BUFSIZE];
     int stringSize;
     while(true)
          {
               stringSize = GetInput(inputBuf); //input is a string
               //printf("%s/n",inputBuf);
               reportSame(inputBuf,stringSize);
          }
     return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值