• C 寻找重复字符并输出他们的位置


     #include <stdio.h>
     #include <string.h>
     #include <stdlib.h>
     
     //给定字串 寻找重复字符  并记录下位置
     //若字串是"0aabb" 则输出a:1 a:2 b:3 b:4
     
     int isExist(char distinct[],char ch);
     int addToExist(char distinct[],char ch);
     int countTimes(char str[],int len,char ch);
     main()
     {
         char str[]="abcaaAB12ab12";
         int i=0;
         char distinct[20];
         for(; i<20; i++)
         {
             distinct[i]=0;
         }
     
         //addToExist(distinct,'a');
         //printf("%c",distinct[0]);//ok
     
         int len=strlen(str);
         //printf("%d",isExist(distinct,str[0]));//ok
         for(i=0; i<len; i++)
         {
             int isEx=isExist(distinct,str[i]);//存在则是1
     
             //遇到新字符 放入到distinct中去
             //然后统计该字符出现次数
             if(!isEx)
             {
                 //printf("not %c",str[i]);//ok
                 addToExist(distinct,str[i]);
                 countTimes(str,len,str[i]);
             }
             else
             {
                 //越过
             }
     
         }
     }
     
     
     int isExist(char distinct[],char ch)
     {
         int i=0;
         int yes=0;//该字符是否已经存在
         for(; i<20; i++)
         {
             if(distinct[i]==ch)
             {
                 yes=1;
                 break;
             }
         }
         return yes;
     }
     
     /**
     新字符加入到最有一个有效字符之后
     也就是放在第一个ASCII为0的位置  先前已经将distinct数组所有元素赋值为0
     */
     int addToExist(char distinct[],char ch)
     {
         int i=0;
         char st;
         while( (st=distinct[i])!=0 )
         {
             i++;
         }
         distinct[i]=ch;
         return ++i;
     
     }
     
     /**
     注意只有重复字符才输出他们的位置
     */
     int countTimes(char str[],int len,char ch)
     {
         int i=0;
         int countChar=0;
         for(; i<len; i++)
         {
             if(str[i]==ch)
             {
                 //printf("%c:%d,",ch,i);
                 countChar++;
             }
     
         }
         if(countChar>1)
         {
             for(i=0; i<len; i++)
             {
                 if(str[i]==ch)
                 {
                     printf("%c:%d,",ch,i);
                 }
     
             }
         }
         return countChar;
     }
  • 相关阅读:
    二、编写输出“Hello World”
    实验一:JDK下载与安装、Eclipse下载与使用总结心得
    C++引用
    数组类型与sizeof与指针的引用
    电源已接通,未充电
    改变Web Browser控件IE版本
    “stdafx.h”: No such file or directory
    word2013 blog test
    Editplus配置VC++(1) 及相关注意事项
    VC++6.0在Win7以上系统上Open或Add to Project files崩溃问题 解决新办法
  • 原文地址:https://www.cnblogs.com/cart55free99/p/2959210.html
Copyright © 2020-2023  润新知