You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart循环使用replaceAll进行替换加密结果异常问题求助

问题原因与解决方法

问题根源

你代码里的核心问题是在循环中反复调用replaceAll:

每次循环都会把文本中所有匹配当前字母表字符的内容替换成密码表字符,但密码表的字符本身就是原字母表的成员。当循环到后面的字母时,之前替换出来的密码字符会被当成原字母再次替换,最终导致结果彻底混乱。

举个例子:
输入abcdef,前几步会把a换成q,但当循环到处理字母q(对应alphabet[16])时,又会把文本里的q换成cypher[16]对应的d——这种多次替换叠加起来,就得到了错误的jvmkmn。

正确写法

应该逐个处理输入文本的每个字符,只做一次替换映射,避免二次替换:

写法一:基础循环实现

import 'dart:io';
import 'dart:convert';

void main(List<String> args) {
  String alphabet = 'abcdefghijklmnopqrstuvwxyz';
  String cypher = 'qwertyuiopasdfghjklzxcvbnm';

  print('entertext:');
  String text = stdin.readLineSync(encoding: utf8)!;

  String result = '';
  for (int i = 0; i < text.length; i++) {
    String char = text[i];
    int index = alphabet.indexOf(char);
    // 字符在字母表里就替换,否则保留原字符
    if (index != -1) {
      result += cypher[index];
    } else {
      result += char;
    }
  }
  print(result);
}

写法二:Dart风格的映射实现

import 'dart:io';
import 'dart:convert';

void main(List<String> args) {
  String alphabet = 'abcdefghijklmnopqrstuvwxyz';
  String cypher = 'qwertyuiopasdfghjklzxcvbnm';

  print('entertext:');
  String text = stdin.readLineSync(encoding: utf8)!;

  String result = text.split('').map((char) {
    int index = alphabet.indexOf(char);
    return index != -1 ? cypher[index] : char;
  }).join();

  print(result);
}

两种写法的核心逻辑都是:遍历输入的每个字符,找到它在原字母表中的位置,直接用密码表对应位置的字符替换,每个字符只处理一次。这样输入abcdef就能得到预期的qwerty。


内容的提问来源于stack exchange,提问作者Lucas Leite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:18:18