使用C语言解决Codewars消息解码问题时遇随机字符异常求助
Codewars解码题目随机测试失败问题分析
我用C语言解决Codewars上的“decoding a message”题目时,代码能通过示例测试,但随机测试会在解码结果末尾出现额外的随机字符。我的实现代码如下:
#include <string.h> #include <ctype.h> char *decode (const char *encoded, char *decoded) { for (int i = 0; i < strlen(encoded); i++) { if (isalpha(encoded[i])) { if (encoded[i] <= 109) { decoded[i] = encoded[i] + 25 - ((encoded[i] - 'a')*2); } else if (encoded[i] >= 110) { decoded[i] = encoded[i] - 25 + (('z' - encoded[i])*2); } } else { decoded[i] = encoded[i]; } } return decoded; // return it }
问题原因
核心问题是没有给解码后的字符串添加C语言字符串必需的终止符\0。C语言中,字符串是以\0作为结束标记的,如果你只把解码后的字符写入decoded数组,却没有在最后补上\0,程序读取字符串时会一直往后读内存里的随机垃圾数据,直到碰到某个\0为止——这就是你看到额外随机字符的原因。
示例测试没出问题只是运气好:示例测试用的decoded数组,刚好在有效字符后面的内存位置是\0,所以没暴露这个问题,但随机测试时内存里的垃圾数据就被读出来了。
另外你的解码逻辑可以简化:小写字母的解码其实是取与a-z对称的字符,比如a对应z,b对应y,直接用'a' + 'z' - encoded[i]就能算出结果,不需要分两个区间判断,代码更简洁且不容易出错。
修复后的代码
#include <string.h> #include <ctype.h> char *decode (const char *encoded, char *decoded) { int len = strlen(encoded); // 提前计算长度,避免循环里反复调用strlen影响效率 for (int i = 0; i < len; i++) { if (isalpha(encoded[i])) { decoded[i] = 'a' + 'z' - encoded[i]; // 简化的对称映射逻辑 } else { decoded[i] = encoded[i]; // 非字母直接复制 } } decoded[len] = '\0'; // 关键:添加字符串终止符 return decoded; }
内容的提问来源于stack exchange,提问作者Ahmed Nader
相关产品推荐
相关产品推荐

