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

Flutter字母定位游戏问题:重复匹配字母无法全部替换求助

解决Flutter字母游戏中重复字母无法全部匹配的问题

嘿,我来帮你搞定这个问题!你遇到的核心问题是**indexOf()只会返回第一个匹配字符的位置**,所以在循环里每次调用word.toLowerCase().indexOf(key.toLowerCase()),得到的永远是第一个'O'的位置1,自然只有i=1的时候会被加入到positionsFound里,第二个'O'(位置6)完全没被检测到。

问题代码的核心缺陷

在你的循环逻辑里:

int position = word.toLowerCase().indexOf(key.toLowerCase());
if(position == i){
  positionsFound.add(Word(key, position));
  print(position);
}

不管i循环到哪个值,position始终是1,所以只有当i=1时才会触发添加操作,第二个匹配的位置6永远不会被命中。

修复方案:逐个检查每个字符位置

最直接的修复方式是遍历每个字符位置,直接对比当前字符和目标key,这样所有匹配的位置都会被捕获。修改后的代码如下:

String word = 'domingo';
String key = 'o'; // 点击O按钮时触发
List<Word> positionsFound = [];

String _word() {
  // 快速初始化全下划线的字符串
  String wordEmpty = '_' * word.length;
  
  // 遍历每个字符位置,检查是否匹配目标字母
  for (int i = 0; i < word.length; i++) {
    if (word[i].toLowerCase() == key.toLowerCase()) {
      positionsFound.add(Word(key, i));
      print(i); // 现在会输出1和6,符合预期
    }
  }
  
  // 将字符串转为List操作,替换对应位置的下划线(比多次replaceFirst更高效直观)
  List<String> chars = wordEmpty.split('');
  for (var match in positionsFound) {
    chars[match.position] = match.key;
  }
  wordEmpty = chars.join('');
  
  return wordEmpty;
}

class Word {
  String key;
  int position;
  Word(this.key, this.position);
}

另一种方案:循环查找所有匹配位置

如果你不想逐个遍历字符,也可以用indexOf的第二个参数(起始查找位置)来循环找出所有匹配的位置:

// 替换原来的循环查找逻辑
int currentPos = word.toLowerCase().indexOf(key.toLowerCase());
while (currentPos != -1) {
  positionsFound.add(Word(key, currentPos));
  print(currentPos);
  // 从当前位置的下一个索引开始继续查找
  currentPos = word.toLowerCase().indexOf(key.toLowerCase(), currentPos + 1);
}

这种方式会不断从上次找到的位置后面继续查找,直到找不到匹配的字符为止,同样能捕获所有重复的字母位置。

额外优化点

  • 初始化wordEmpty时用'_' * word.length比循环拼接更简洁高效
  • 用List来修改字符位置比多次调用replaceFirst更可靠,避免因字符串操作带来的位置歧义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:26:53