Level 1 : Project 2
In order to secure the messages to be sent, an encryption method can be used.
One of the methods used consists in replacing each letter of the message to be encrypted by the one that follows it from p positions in the English alphabet, where p denotes the number of words in the message.
Note:
-
It is assumed that the character which follows the letter " Z " is the character " A " and that which follows the letter " z "is the " a " character.
-
The space character is not modified.
-
The ASCII code of the letter " a " is equal to 97 and that of the letter " A " is equal to 65.
Example:
For the message " The Second Project Of Level One "
Since the message to be encrypted is made up of 6 words, for the alphabetical letter " T " for example, it will be replaced by " Z " because by adding to the Ascii code of " T " which is 84 the value 6, we obtain 90 whichis the Ascii code of " Z ".
By continuing to apply this coding principle, the encrypted message will be:
" Znk Ykiutj Vxupkiz Ul Rkbkr Utk "
We propose to write a Dart program which allows you to enter a message "msg" formed only letters and spaces and then display it encrypted, using the principle cited above.
Solution:
import 'dart:io';
String enterMessage() {
String txt;
do {
print("Enter a message formed only letters and spaces ");
txt = stdin.readLineSync();
//check if txt formed only letters and spaces
if (txt != null) {
for (int i = 0; i < txt.length; i++) {
if (txt[i] != ' ') {
if (!((txt.toUpperCase().codeUnitAt(i) >= 65) &&
((txt.toUpperCase().codeUnitAt(i) <= 90)))) {
txt = null;
break;
}
}
}
}
} while (txt == null);
return txt;
}
int wordsNumber(String txt) {
var words;
if (txt[0] != ' ')
words = 1;
else
words = 0;
for (int i = 0; i < txt.length - 1; i++) {
if ((txt[i] == ' ') && (txt[i + 1] != ' ')) words++;
}
return words;
}
void encryption(String txt, int p) {
var encryptedMsg = "";
for (int i = 0; i < txt.length; i++) {
if (txt[i] == ' ')
encryptedMsg += " ";
else {
var ascii = txt.codeUnitAt(i);
//UpperCase
if (ascii <= 90) {
if ((ascii + p) > 90)
encryptedMsg += String.fromCharCode(ascii + p - 26);
else
encryptedMsg += String.fromCharCode(ascii + p);
}
//LowerCase
if (ascii >= 97) {
if ((ascii + p) > 122)
encryptedMsg += String.fromCharCode(ascii + p - 26);
else
encryptedMsg += String.fromCharCode(ascii + p);
}
}
}
print(encryptedMsg);
}
void main() {
var msg, p;
msg = enterMessage();
p = wordsNumber(msg);
encryption(msg, p);
}
The Second Project Of Level One
Znk Ykiutj Vxupkiz Ul Rkbkr Utk