Start learning free

LESSON 141 OF 347 · LOOPS & GLOBAL VARIABLES

Hacker Speak in C#: Replacing Characters in a String

Practice Read the full explanation

Given a string, write a function that returns a coded (h4ck3r 5p34k) version of the string.

In order to work properly, the function should replace all "a"s with 4, "e"s with 3, "i"s with 1, "o"s with 0, and "s"s with 5.

Example 1:

Input:  "javascript is cool"

Output: "j4v45cr1pt 15 c00l"

Example 2:

Input:  "programming is fun"

Output: "pr0gr4mm1ng 15 fun"

Example 3:

Input:  "become a coder"

Output: "b3c0m3 4 c0d3r"
Hints:

We have to iterate through every character of input, check for each scenario and treat it accordingly:
  • Is it an 'a'? If so, replace with '4'. Otherwise:
  • Is it an 'e'? If so, replace with '3'. Otherwise:
  • Is it an 'i'? If so, replace with '1'. Otherwise:
  • Is it an 'o'? If so, replace with '0'. Otherwise:
  • Is it an 's'? If so, replace with '5'. Otherwise, keep it as it is.
Remember that strings are immutable. How does that affect us? How can we put this strategy into code?

Strings are immutable means you cannot directly change a character in a string like this: input[4] = '4'. This means we have to create a new string where we will store the solution as we create it. How can we translate these two hints in code?

Let's create a new string named solution, initially empty, where we will push all the encoded characters of input. We will use a for loop and a character variable c to iterate through input and treat the scenarios inside the loop:
solution = ""
for each c in input:
	if c == 'a':
        solution += '4'
    else if c == 'e':
        solution += '3'
    else if c == 'i':
        solution += '1'
    else if c == 'o':
        solution += '0'
    else if c == 's':
        solution += '5'
    else:
        solution += c
return solution


We have a for loop that performs exactly n iterations (n is the length of input), thus the Time Complexity is O(n).
The extra space we use is the extra string solution. Its length will be n in the end, thus the Extra Space used is also O(n).
STEP 1 OF 9
    Ctrl + Enter to check

    C# · LOOPS & GLOBAL VARIABLES

    Hacker Speak in C#, explained

    Problem overview

    ConvertToHackerSpeak(string input) returns a coded copy of input in which five letters are swapped for look-alike digits:

    LetterBecomes
    a4
    e3
    i1
    o0
    s5

    Every other character, including spaces, stays as it is. For example, "become a coder" turns into "b3c0m3 4 c0d3r", and "javascript is cool" turns into "j4v45cr1pt 15 c00l".

    Approach: build a new string one character at a time

    The plan is to walk through the input from left to right. For each character, decide what to put in the result: the matching digit if it is one of the five letters, or the character itself otherwise. The decision is a chain of "is it an a? otherwise, is it an e?" questions, and exactly one branch applies to each character.

    The result has to be a new string, because C# strings are immutable: once created, a string can't be changed. Writing input[4] = '4' is a compile error, since the indexer is read-only. So the method starts with an empty string and extends it as the loop goes.

    Step by step

    1. Start with an empty string. string solution = ""; collects the encoded text.
    2. Loop over the characters. The lesson uses foreach (char c in input.ToCharArray()). ToCharArray() copies the string into a char[], and foreach then gives you each char in turn.
    3. Handle 'a'. If c == 'a', append '4'. Single quotes make a char literal, which is the same type as c, so the comparison is between two characters.
    4. Handle 'e', 'i', 'o' and 's'. Each is an else if in the same chain, appending '3', '1', '0' and '5'. An else if is only tested when every condition above it was false, so one character triggers one branch.
    5. Keep everything else. The final else appends c unchanged, so spaces, consonants, digits and punctuation survive.
    6. Return the result after the loop, once every character has been processed.

    The solution in C#

    class Solution {
        public string ConvertToHackerSpeak(string input) {
            string solution = "";
            foreach (char c in input.ToCharArray()) {
                if (c == 'a') {
                    solution += '4';
                } else if (c == 'e') {
                    solution += '3';
                } else if (c == 'i') {
                    solution += '1';
                } else if (c == 'o') {
                    solution += '0';
                } else if (c == 's') {
                    solution += '5';
                } else {
                    solution += c;
                }
            }
            return solution;
    
        }
    }
    

    Details worth knowing:

    • += on a string creates a new string. solution += '4' builds a new string that is one character longer and stores it back in solution. The old string is discarded. Appending a char to a string works, and the character is added as text.
    • Single quotes versus double quotes. 'a' is a char and "a" is a string. Comparing c == "a" doesn't compile, because a char and a string can't be compared with ==.
    • The ToCharArray() call is optional. A string is already a sequence of char values, so foreach (char c in input) behaves the same and skips the copy.
    • Digits are not added as numbers. The results here are the characters '4', '3' and so on. Writing solution += 4 with an int would also append the text "4", but mixing a char with an int in arithmetic, such as 'a' + 1, produces the number 98. It is safest to stay with characters and strings.
    • A shorter way to write the chain. A switch statement does the same job, with one case for each letter. The if chain keeps the lesson's focus on conditions in a loop.

    Why repeated += can be slow

    Because each += copies the whole string so far, building a long result this way takes quadratic time: copying 1 character, then 2, then 3, up to n. For typical lesson inputs this is invisible. For very long texts, System.Text.StringBuilder is the standard answer: its Append method adds to an internal buffer, and ToString() produces the final string once.

    Here is the same logic written with a switch and a StringBuilder. It follows the same plan, and it builds the output without copying the string on every step:

    using System.Text;
    
    StringBuilder result = new StringBuilder();
    foreach (char c in input) {
        switch (c) {
            case 'a': result.Append('4'); break;
            case 'e': result.Append('3'); break;
            case 'i': result.Append('1'); break;
            case 'o': result.Append('0'); break;
            case 's': result.Append('5'); break;
            default: result.Append(c); break;
        }
    }
    return result.ToString();
    

    On the input "become a coder is easy" this version returns "b3c0m3 4 c0d3r 15 345y". Each case must end with break, because C# does not allow execution to fall from one case into the next.

    Complexity

    Time. The loop runs n times, once per character, and the checks inside are constant time. With the string concatenation as written, the copying makes the real cost up to O(n²) in the worst case. With a StringBuilder it is O(n).

    Space: O(n). The result has the same length as the input, plus the copy made by ToCharArray().

    Edge cases and common mistakes

    • Uppercase letters. The comparisons are case-sensitive, so "Apple Sauce" becomes "Appl3 S4uc3": the capital A and S are left alone. The lesson only asks for lowercase letters.
    • Empty string. The loop doesn't run, and the method returns an empty string.
    • Unchanged characters. Leaving out the final else would drop every space and consonant from the output.
    • Using separate if statements instead of else if. Each if would be tested on its own, and the final else would belong only to the last one (the test for 's'). Every character except s would then also be appended unchanged, so 'a' would produce both 4 and a. The else if chain ties all the branches together so that exactly one runs.
    • Trying to modify the input. Strings can't be changed in place, and the method has to return a new one.

    Testing

    • "javascript is cool" gives "j4v45cr1pt 15 c00l".
    • "programming is fun" gives "pr0gr4mm1ng 15 fun".
    • "become a coder" gives "b3c0m3 4 c0d3r".
    • "xyz" gives "xyz", since none of its letters are replaced.
    • "" gives "".
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free