我编写了一个循环,使用引用数组将字符串中的每个字符替换为另一个字符。
for(int i=0 ; i < encoded_message_len ; i++){
for(int j=0; j < 26 ; j++){
if(encoded_message_copy[i] == substitution_alphabet[j]){
printf("%c ->>>> %c @ index:%d \n",encoded_message_copy[i], original_alphabet[j], i);
encoded_message_copy[i] = original_alphabet[j];
}
}
}
然而,当我运行这段代码时,我得到了一个奇怪的输出:
J ->>>> C @ index:0
H ->>>> R @ index:1
Q ->>>> Y @ index:2
Y ->>>> Z @ index:2
S ->>>> P @ index:3
U ->>>> T @ index:4
T ->>>> V @ index:4
X ->>>> O @ index:6
F ->>>> L @ index:7
L ->>>> X @ index:7
X ->>>> O @ index:8
B ->>>> G @ index:9
G ->>>> W @ index:9
Q ->>>> Y @ index:10
Y ->>>> Z @ index:10
当我从循环中删除此行:encoded_message_copy[i] = original_alphabet[j];
时,我得到了预期的输出:
J ->>>> C @ index:0
H ->>>> R @ index:1
Q ->>>> Y @ index:2
S ->>>> P @ index:3
U ->>>> T @ index:4
X ->>>> O @ index:6
F ->>>> L @ index:7
X ->>>> O @ index:8
B ->>>> G @ index:9
Q ->>>> Y @ index:10
谁能解释为什么会这样?
在需要删除以使其正确的行之后放置一个 break;
(在 for 循环内)
你改变了encoded_message_copy
的内容,这会导致语句if(encoded_message_copy[i] == substitution_alphabet[j])
多次匹配同一个值我
;-)
我是一名优秀的程序员,十分优秀!