By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,727 Members | 1,268 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,727 IT Pros & Developers. It's quick & easy.

need some correction in implementing TrimLeft(wchar_t*)

bajajv
100+
P: 152
This is my code -

i/p is L"!?%@ VIPUL"
o/p is @ VIPUL.
desired o/p is VIPUL

Not getting the correct o/p.

Expand|Select|Wrap|Line Numbers
  1. class CString 
  2. public:
  3.     wstring wStr; 
  4.                 int getLength();
  5.                 CString& TrimLeft(wchar_t* wcChar);
  6. };
  7.  
  8. CString& CString::TrimLeft(wchar_t* wcChar)
  9. {
  10.     wstring::iterator iterCString = wStr.begin();
  11.     int iLength = this->getLength();
  12.     wchar_t* wcTemp = wcChar;
  13.  
  14.     while (*wcTemp != L'\0')
  15.     {
  16.         if (*iterCString == *wcTemp)
  17.         {
  18.             wStr.erase(0, 1);
  19.             iterCString++;
  20.             wcTemp = wcChar;
  21.             iLength = this->getLength();
  22.         }
  23.         else
  24.         {
  25.             wcTemp++;            
  26.         }
  27.     }
  28.     return *this;
  29. }
  30.  
  31. int main()
  32. {
  33.          CString name = L"!?%@ VIPUL";
  34.     wcout<<name.wStr<<endl;
  35.     wchar_t wcArray[5];
  36.     wcArray[0] = L'%';
  37.     wcArray[1] = L'!';
  38.     wcArray[2] = L'?';
  39.     wcArray[3] = L'@';
  40.     wcArray[4] = L' ';
  41.     name.TrimLeft(wcArray);
  42.     wcout<<name.wStr<<endl;
  43.     return 0;
  44. }
Dec 21 '09 #1
Share this Question
Share on Google+
3 Replies


bajajv
100+
P: 152
Got the answer.

No need for incrementing iterator in If-else condition. Since it is set to the beginning of the string, it will automatically increment whenever first letter of wstring is deleted.

Well, plz correct me if I am wrong, but it is working that way..... :))
Going to consult some text.
Dec 21 '09 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
Expand|Select|Wrap|Line Numbers
  1. wStr.erase(0, 1); 
  2.             iterCString++; 
The erase invalidates the iterator.
Dec 21 '09 #3

RRick
Expert 100+
P: 463
The correct use of erase is
Expand|Select|Wrap|Line Numbers
  1.  iterCString = wStr.erase(0, 1);
But there are other issues here. When you find a bad wchar, you always erase the first wchar in the string. You probably want to erase the wchar at the iterator position.
Expand|Select|Wrap|Line Numbers
  1.  iterCString = wStr.erase( iterCString);
Dec 21 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.