[英]decoding message using c
我正在使用 C 解決一個名為“解碼消息”的代碼戰問題。
我的代碼通過了樣本測試,但無法通過隨機測試,因為它在圖像中所需的字符后添加了隨機字符,如在此處輸入圖像描述
這里有什么問題?
問題鏈接:[https://www.codewars.com/kata/565b9d6f8139573819000056]
#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
}
如評論中所示,OP 描述的症狀表明接收緩沖區未正確終止以生成 C 字符串。
此外,應該避免在代碼中使用像 109 和 110 這樣的“幻數”……這些數字是什么意思? 如果取消“全部小寫”的限制,它們肯定不會工作。 是否會復制/粘貼/改編多行代碼只是為了處理大寫和小寫字母?
下面是 LESS 代碼,它不僅處理 OP 問題(未終止的字符串),而且還處理大寫和小寫字母(認識到“大小寫”會削弱任何加密。包含在此處僅用於演示技術。)
享受這些學習挑戰帶來的樂趣。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *decode( const char *s, char *d ) {
for( size_t i = 0; ( d[i] = s[i] ) != '\0'; i++ ) { // copy every byte
if( isalpha( d[i] ) ) { // transform needed ?
char c = islower( d[i] ) ? 'a' : 'A'; // basis to transpose ASCII char to 0-25
d[i] = (char)( c + ( 25 - ( d[i] - c ) ) ); // 0->25 ==> 25->0
}
}
return d; // return it
}
int main() {
char *hidden = "R slkv MLYLWB wvxlwvh gsrh nvhhztv";
char buf[ 128 ];
printf( "%s\n%s\n", hidden, decode( hidden, buf ) );
return 0;
}
R slkv MLYLWB wvxlwvh gsrh nvhhztv
I hope NOBODY decodes this message
如果有任何不清楚的地方,請在下面發表問題...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.