DSA Factory
Free lessonsProgramming basics · Stage 6 · Text · Step 1

Letters by position

Pick letters out of a word by their position, and join pieces together. About 9 minutes.

A row of letters

A piece of text, which programmers call a string, is a row of letters in numbered boxes. Spaces and punctuation get a box too. You find a letter by its position, and here is the surprise: the first letter is at position 0, not 1.

So in the word "plane" the p is at position 0, the l at 1, and the e at 4. The last letter is always at the position one less than the length of the word.

Counting starts at 0: the first letter is at position zero.
In code
word = "plane"
first = word[0]      # "p"
last = word[4]       # "e"
Moving the first letter to the end
p
0
l
1
a
2
n
3
e
4
position
first
p

The letter at position 0 is the first letter. It is p.

Move 1 of 3

Cutting and joining

You can cut a piece off a string, and you can glue pieces together with a plus sign. Joining strings is called concatenation, which is a long name for a simple idea.

To move the first letter to the end of a word, do three things. Pick out the first letter. Cut off everything after it. Then glue the rest first and the first letter second. Each language has its own way of cutting. Your editor shows the one for your language.

A plus sign: between two strings glues them together.
In code
word = "plane"
first = word[0]
rest = word[1:]      # "lane"
new_word = rest + first
Quick check

word is "plane". Positions start at 0. Which letter is at position 2?

  1. Aa
  2. Bl
  3. Cn
Show the answer

a. p is at 0, l is at 1, and a is at 2.

Your problem

Rotate by one

Move the first letter of a word to the end, and return the new word. For example "hello" becomes "elloh". A word with fewer than two letters stays as it is.

Example
s = "hello" → "elloh"

0 ≤ length of s ≤ 1,000 · lowercase letters only

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding