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

Building new text

Make a new string one piece at a time, with separators in the right places. About 9 minutes.

Start with nothing, add pieces

To build a new piece of text, start with an empty string, which is just a pair of quotes with nothing between. It is like a blank page. Then add to it, one piece at a time, with a loop.

In each pass, glue the next piece onto the end of the string. When the loop finishes, the page is full and you return it. You never change the original text. You are writing a fresh copy, with your own changes in it.

Start with an empty string, and glue pieces onto the end.
In code
result = ""
for ch in s:
    result = result + ch

Separators go between

Say you want to spread a word out with spaces, so that "abc" becomes "a b c". It is tempting to add a space after every letter. But then the result ends with a space too: "a b c ". That is wrong.

A space belongs between the letters, not after the last one. The trick: before you add a letter, check whether the result is still empty. If it isn't, add the space first. The very first letter then gets no space.

Separators go between pieces: not before the first or after the last.
In code
result = ""
for ch in s:
    if result != "":
        result = result + " "
    result = result + ch
Spreading out "abc"
a
0
b
1
c
2
letter
result
a

The result starts empty. For the first letter, the result is empty, so no space is added first. Just add a.

Move 1 of 3
Quick check

You spread out the word "hi" with a single space between letters. How many characters does the result have?

  1. A3
  2. B4
  3. C2
Show the answer

3. h, a space and i make three characters.

Your problem

Spread it out

Return the text with a single space between each pair of letters. There should be no space before the first letter or after the last. An empty text stays empty.

Example
s = "abc" → "a b c"

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