[英]Decoding character array using custom alphabet in C
#include<stdio.h>
int main(){
int i,j;
char kulcs[27]="DKVQFIBJWPESCXHTMYAUOLRGZN",kod='D',szoveg[256]="fndcdahqweehufsfnhtyhbydchcdcwEHQHSfaQFEHQHS";
if(kod=='D'){
for(i=0;kulcs[i]!='\0';i++){
for(j=0;szoveg[j]!='\0';j++){
if(kulcs[i]==szoveg[j]){
szoveg[j]=i+65;
}else if(kulcs[i]==szoveg[j]-32){
szoveg[j]=i+97;
}
}
}
printf("%s\n",szoveg);
}
return 0;
}
kulcs
stores the alphabet, szoveg
is the word I want to decode, while keeping upper and lower case letters intact. kulcs
存储字母表, szoveg
是我想要解码的单词,同时保持大写和小写字母不变。
expected result:预期结果:
ezamasodikkotelezoprogramomamiKODOLesDEKODOL
what the code does is:代码的作用是:
kzsqssudikkutkvkzupwuxwsquqsqiKUDUVksDKKUDUV
What did I do wrong?我做错了什么?
Your loops are in the wrong order.您的循环顺序错误。 You loop through the alphabet and inside that loop you loop through the word.
您遍历字母表,然后在该循环中遍历单词。 Think what happens.
想想会发生什么。
An example:一个例子:
Let's say the transformations are假设转换是
A->B
A->B
B->C乙->丙
You input word ABC您输入单词 ABC
Your code starts looping through the transformations.您的代码开始遍历转换。 First it checks all A's and changes them to B's, so you get BBC.
首先它检查所有 A 并将它们更改为 B,这样你就得到了 BBC。 Then it checks all B's and transforms them to C's, so you get CCC.
然后它检查所有 B 并将它们转换为 C,所以你得到 CCC。
What you should do is loop through the input and check which transform fits.您应该做的是遍历输入并检查哪个转换适合。 In this example you first get A, check that there's a transform A->B, so this becomes B. Your output is just B. Then there's a B, which must be transformed into C, so you have now BC.
在这个例子中,你首先得到 A,检查是否有 A->B 变换,所以它变成了 B。你的输出只是 B。然后有一个 B,它必须转换成 C,所以你现在有 BC。 Then is C, no transform, so it's BCC.
然后是 C,没有变换,所以它是 BCC。
So change the j
and i
loops around and see what happens.所以改变
j
和i
循环,看看会发生什么。
for(j=0;szoveg[j]!='\0';j++){
for(i=0;kulcs[i]!='\0';i++){
Also you can break the loop if either of the conditions fits, since there won't be another suitable condition after that.如果其中一个条件满足,您也可以中断循环,因为在此之后不会有另一个合适的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.