题解 | #字符串加密#
字符串加密
http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
这里我遇到一个问题,就是在去重的时候,使用strcpy出了问题,所以自己写了mystrcpy,问题解决了。为什么strcpy在同一个字符串内部,从高地址复制到低地址会出问题?有大佬知道吗
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int prepare_key(char *key);
void encrypt(char *data, char const *key);
int main(){
char key[501];
char uncrypt[501]; // 明文
scanf("%s", key);
scanf("%s", uncrypt);
/* 生成密钥 */
prepare_key(key);
/* 加密 */
encrypt(uncrypt, key);
printf("%s\n", uncrypt);
return 0;
}
static char *mystrcpy(char *dst, char const *src){
char *ret =dst;
while ((*dst++ = *src++) != '\0')
;
return ret;
}
/* desc: 对data中的字符,用key来加密,非字母字母不做修改,
* 加密前后不改变大小写
* 结果保存在data中
**/
void encrypt(char *data, char const *key){
int c;
for (; *data != '\0'; data++){
if (!isalpha(*data))
continue;
c = *(key + toupper(*data) - 'A');
*data = isupper(*data) ? c : tolower(c);
}
}
/* desc : 根据key中的单词,生成密钥存放在key中
* 密钥是大写的
* retval:0 for failed, 1 for success
**/
int prepare_key(char *key){
int c;
char *keyp, *dup;
/* 将key转换成大写 */
for (keyp = key; *keyp != '\0'; keyp++)
if (isalpha(*keyp))
*keyp = toupper(*keyp);
else
return 0;
/* 去重 */
for (keyp = key; (c = *keyp) != '\0';){
dup = ++keyp;
while ((dup = strchr(dup, c)) != NULL)
mystrcpy(dup, dup+1);
}
for (c = 'A';
c <= 'Z'; c++){
if (strchr(key, c) == NULL){
*keyp++ = c;
*keyp = '\0';
}
}
return 1;
}