We help IT Professionals succeed at work.

need a Ltrim function in c++

hpchong7
hpchong7 asked
on
Dear all,

   I need two function:Ltrim and Rtrim in c++.Full code.Thank you very much!
Comment
Watch Question

AxterSenior Software Engineer

Commented:
Do you need it to trim a string or just a charactor?
AxterSenior Software Engineer

Commented:
char* TrimRight(char* Src, char Item)
{
     for (int i = strlen(Src)-1;i;i--)
     {
          if (Src[i] == Item) Src[i] = 0;
     }
     return Src;
}

Author

Commented:
I need the trim function just like those from VB,trim trailing and leading space.
AxterSenior Software Engineer

Commented:
char* TrimLeft(char* Src, char Item)
{
     while(Src[0] == Item) strcpy(Src,Src+1);
     return Src;
}

AxterSenior Software Engineer

Commented:
Correction on TrimRight code:

char* TrimRight(char* Src, char Item)
{
     while(Src[strlen(Src)-1] == Item) Src[strlen(Src)-1] = 0;
     return Src;
}
AxterSenior Software Engineer

Commented:
Example code:
void SomeFunction(void)
{
     char test[] = "yyyyy  Hello there baby  xxxx";
     TrimRight(test,'x');
     TrimLeft(test,'y');

     //Trim spaces
     TrimRight(test,' ');
     TrimLeft(test,' ');
}

By putting a space as the second argument, you can make it trim leading and trailing spaces.

Author

Commented:
Do your trim functions work if there is both space and tab before and after the string(I just want to call the function once)
Senior Software Engineer
Commented:
The following version of the code will remove both in one pass.

char* TrimRight(char* Src)
{
     while(Src[strlen(Src)-1] == ' ' || Src[strlen(Src)-1] == '\t') Src[strlen(Src)-1] = 0;
     return Src;
}

char* TrimLeft(char* Src)
{
     while(Src[0] == ' ' || Src[0] == '\t') strcpy(Src,Src+1);
     return Src;
}


I took out the second argument since you just wanted it for spaces and tabs.
AxterSenior Software Engineer

Commented:
hpchong7,
Did that give you what you needed?

Author

Commented:
No, your code has bug at the line strcpy:unhandle exception access violation.

Author

Commented:
Oh sorry, it's my problem.I initialise the string by
char *tmp = " abc " and pass tmp into the function so there is error.
AxterSenior Software Engineer

Commented:
>>Oh sorry, it's my problem.I initialise the string by

So are you satisfied with the functions?

Explore More ContentExplore courses, solutions, and other research materials related to this topic.