• 李春葆《数据结构教程》上机实验题4.***编码实现 - [方法论]

    2009-04-16

    分类: 方法论

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://skyofcai.blogbus.com/logs/37951842.html

    (声明: 该代码经过测试,但不能排除一切bug。任何人使用且发现bug并造成的一切损失,将由使用本代码者承担全部责任,而本作者不承担任何责任。该代码仅供学习交流。若能将bug报告给本作者,在下会感激不尽。)

    代码如下:

    ////////////////////////////////////////////////////////
    // title   : codingAndDecoding.c
    // content : 该算法实现来自于李春葆编写的《数据结构》
    //           一书中的第4章的上机实验题的第4题。
    //           要求根据字母映射表编写一个算法:将输入的
    //           文本串进行加密后输出。再编写一个算法:
    //           将输入的已加密的文本串进行解密后输出。
    // author  : Henry
    // date    : 2009-04-16
    // version : v1.0
    ///////////////////////////////////////////////////////

    #include <stdio.h>
    #include <string.h>
    #define MaxSize 20                                     //允许输入字符串的最大长度
    char* coding(char* str);                              //加密
    char* decoding(char* pwd);                         //解密
    int locate(char* str, char c);                         //定位字符下标
    char a[] = "abcdefghijklmnopqrstuvwxyz";     //字母表
    char b[] = "ngzqtcobmuhelkpdawxfyivrsj";     //映像表
    int main(void)
    {
          char s[MaxSize];
          printf("Please input a string : \n");
          scanf ("%s",s);
          printf("The input code      : %s\n", s);
          printf("The coding string   : %s\n", coding(s));
          printf("The s is            : %s\n", s);
          printf("The decoding string : %s\n", decoding(s));
          return 0;
    }

    char* coding(char* str)             //str不能是指向常量字符串
    {
          int k, i = 0;
          while(str[i] != '\0')
         {
               k = str[i] - 'a';               //k保存字符在字母表中的下标
               str[i] =  b[k];                //由映射关系根据下标在映像表中取字符
               i++;
          }
          return str;
    }

    char* decoding(char* pwd)         //str不能是指向常量字符串
    {
           int k, i = 0;
           while (pwd[i] != '\0')
           {
                    k = locate(b,pwd[i]);   //k保存字符在映像表中的下标
                   pwd[i] = a[k];             //根据映像关系和下标在字母表中取字符
                   i++;
            }
            return pwd;
    }

    int locate(char* str, char c)         //顺序搜素映像表查找字符下标
    {
             int i = 0;
             while(str[i] != '\0')
            {
                  if (str[i] == c)
                         return i;
                  i++;
             }
             return -1;
    }


    收藏到:Del.icio.us