Thread: How to improve left trim function?

  1. #1
    Registered User
    Join Date
    Nov 2013
    Posts
    107

    How to improve left trim function?

    This works, if just loops through till it doesn't find a space or tab than counts the index at that point then uses substr to get rid of any spaces/tabs, it's a small function and uses a goto I am just wondering how you would do it?

    Code:
    string trimLeft(string lineOfCodeToTrim){
        string l = lineOfCodeToTrim;
        int k =0;
        
        for(UINT i = 0;i<l.length();i++){
            //FIXME: Just need l[i] != ' ' && l[i] != '\t";
            if(((int)l[i] < 32 || (int)l[i] > 32) && ((int)l[i] != 9)){
                goto l1;
                }
            k++;
            }
    l1:
        if(k > 0){
            l = l.substr(k ,lineOfCodeToTrim.length() - k);
            }
        return l;
        }

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    void LeftTrim(string &s)
    {
        const char ToTrim[] = " \t";
        s.erase(0, s.find_first_not_of(ToTrim));
    }//LeftTrim
    
    int main()
    {
        string s = "\t   Hello\tWorld\t ";
        LeftTrim(s);
        cout << "[" << s << "]"<< endl;
        return 0;
    }//main
    gg

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by jim_0 View Post
    Code:
            if(((int)l[i] < 32 || (int)l[i] > 32) && ((int)l[i] != 9))
    Blech! Magic values (like 32 and 9) are not a good idea, since different character sets use different values for things like spaces and tabs.

    The expression "a < b || a > b" is more easily expressed as "a != b" too.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Critique my trim function
    By atac in forum C Programming
    Replies: 4
    Last Post: 11-17-2013, 03:59 PM
  2. [C] trim function serious implementation
    By triceps in forum C Programming
    Replies: 10
    Last Post: 09-12-2011, 04:18 PM
  3. trim function - could you explain please
    By c_lady in forum C Programming
    Replies: 17
    Last Post: 03-27-2010, 09:19 AM
  4. trim string function (code)
    By ipe in forum C Programming
    Replies: 9
    Last Post: 01-06-2003, 12:28 AM