Search code examples
stringdartencryptioncs50

(dart) replaceAll method in a string in a loop (cypher)


I'm attempting to do CS50 courses in dart, so for week 2 substitution test i'm stuck with this:

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

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

  for (int i = 0; i < n; i++) {
    text = text.replaceAll(alphabet[i], cypher[i]);
  }
  print(text);
}

Expected result: abcdef = qwerty

Actual result: jvmkmn

Any ideas why this is happening? I'm a total beginner by the way


Solution

  • It is because you at first substitute the letter a with the letter q, but when n = 16, you will replace all the letter q with the letter j. This is why your a is turned into a j, and so forth...

    Best of luck to you :)