Back
Close

Ceaser Cipher

Adriaan
3,138 views

Working with text

The String datatype has many useful methods we can use to get information from it.

Let's say we have a string, and we would like to get the 5th letter.

We can use charAt() or [] notation.

Look at the code below:

const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
console.log("The fith letter is: " + ALPHABET.charAt(4));
console.log("The tenth letter is: " + ALPHABET[9]);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Why did we use 4 to get the 5th letter and 9 to get the 10th letter?

Because the String index starts at 0. So ALPHABET.charAt(0) is the first letter, ALPHABET.charAt(1) is the second letter and so on.

The code above lets us find which letter is at a certain position in the String. What if we knew the letter, but wanted to find which position it's in, or what it's index is?

To do that we can use the indexOf() method.

Note, indexOf() returns the first occurance of the given string or character.

Look at the code below:

const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
let position = ALPHABET.indexOf("e") + 1;
console.log("The character \"e\"'s position is " + position);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

In the code below, create a variable called myChar and set it to the character at 59th position of the string myString.

Also create a variable called position and set it equal to the position of the first occurance of the character j

Your Turn
const myString = "dQbQCMYkgMCiwHEZ4MGIU2JPmmSFQyCc3hnL4iqxvMm3CjLMAHSTUtuYygrs8J5twktpkAwcCYuL27EHJLhgdhUqbvvpRCeDFu0D";
// { autofold
module.exports = {myChar: myChar, position: position}
//}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants