All challenges
Easy 0 solved 0% acceptance

Replace Spaces With Dashes

Turn spaces into dashes to make a URL-style slug.

What you'll learn

  • Replace characters while copying a string
  • Build a URL-style slug
  • Compare manual loops with replace methods

Problem

Replace every space in text with a dash -, and convert all letters to lowercase.

Implement slugify_spaces(text).

Input

text: The text to convert.

Output

Return the converted text.

Constraints

0 ≤ length of text ≤ 10,000

Examples

Example 1
Input:
text = "Hello World"

Expected output:
expected = "hello-world"
Input:
std::string text = "Hello World";

Expected output:
std::string expected = "hello-world";
Input:
string text = "Hello World";

Expected output:
string expected = "hello-world";

Explanation

The space becomes a dash and letters are lowercased: "hello-world".

Example 2
Input:
text = "Learn  To Code"

Expected output:
expected = "learn--to-code"
Input:
std::string text = "Learn  To Code";

Expected output:
std::string expected = "learn--to-code";
Input:
string text = "Learn  To Code";

Expected output:
string expected = "learn--to-code";

Explanation

Each space becomes its own dash: "learn--to-code".

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Transform the whole string by applying both lowercase conversion and space replacement.

Hint 2

A single pass can build the result while handling each character.

Hint 3

Be careful not to change non-letter characters except spaces.

Expected complexity

O(n) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.