Trim function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prabu Ramasamy
    New Member
    • Jun 2007
    • 6

    Trim function

    here i kno trim function wil remove first and last whitespaces if occured. but i don the program for that.string wil u pleas explain this program step by step?
    particularly why they take the concept of takin condition >' ' in conditional statement.
    program: i didnt send main,class definition simply function definition
    [code=cpp]
    string StringUtil::Tri m(string givenString)
    {
    int count = givenString.len gth();
    if (count == 0 || (givenString[0] > ' ' && givenString[count-1] > ' '))
    return givenString;

    int preTrim = 0;
    for (;; preTrim++)
    {
    if (preTrim == count)
    return givenString;
    if (givenString[preTrim] > ' ')
    break;
    }
    int endTrim = count;
    while (givenString[endTrim-1] <= ' ')
    endTrim--;
    return this->SubString(give nString, preTrim, endTrim-1);
    };[/code]
    Last edited by JosAH; Jun 4 '07, 02:28 PM. Reason: aded [code=cpp] ... [/code] tags
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    OK. Here you go:

    [code=cpp]
    string StringUtil::Tri m(string givenString)
    {
    //
    //This is a deprecated method. You should use givenString.siz e().
    //None of the other STL containers have a length() but all have a size().
    //
    // VVVVVVVVVVVVVVV VV
    int count = givenString.len gth();
    //
    //So, if the count is zero there oare no characters in the string.
    //There's nothing to trim and the function returns.
    //OR
    //look at both ends of the string. If there's nothing to trim, the function returns.
    //This is done with an expression that says
    //if the first character of the string is greater than a space
    //AND if the last charaacter is greater then a space, then there's
    //nothing to trim and the function returns.
    //
    //Refer to the ASCII table. You will see that all non-space characters
    //are greater than the value of a ' ' (which is 48 by the way).
    //
    if (count == 0 || (givenString[0] > ' ' && givenString[count-1] > ' '))
    return givenString;
    //
    //This section skips over all leading spaces (if any).
    //
    // VVVVVVVVVVVVVVV
    int preTrim = 0;
    for (;; preTrim++)
    {
    if (preTrim == count)
    return givenString;
    if (givenString[preTrim] > ' ')
    break;
    }
    //
    //This section skips over the trailing spaces.
    //
    // VVVVVVVVVVVVVVV VVVVVV
    int endTrim = count;
    while (givenString[endTrim-1] <= ' ')
    endTrim--;
    //
    //Finally, copy from the first non-space through the last non-space
    //and put eh copy back into the original string.
    //
    //VVVVVVVVVVVVVVV VVVVVVVVVVV
    return this->SubString(give nString, preTrim, endTrim-1);
    };
    ]/code]

    Comment

    Working...