Problem of the Day
A new programming or logic puzzle every Mon-Fri

Trim

Today's problem is to implement one of the most popular functions in programming languages, trim. The goal of trim is to remove whitespace from the beginning and end of a string. For bonus points you can make an ltrim and rtrim which remove whitespace only from the left and right respectively. While the worst case for your function should be O(n), you should include optimizations to not check every character if possible.

Permalink: http://problemotd.com/problem/trim/

Comments:

  • Anonymous - 3¬†years, 4¬†months ago

    def ltrim(word1):
        i = 0
        while word1[i] == " ":
            i = i + 1
        return word1[i:]
    
    def rtrim(word2):
        word3 = word2[::-1]
        return ltrim(word3)[::-1]
    
    

    reply permalink

Content curated by @MaxBurstein