need some correction in implementing TrimLeft(wchar_t*)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bajajv
    New Member
    • Jun 2007
    • 152

    need some correction in implementing TrimLeft(wchar_t*)

    This is my code -

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

    Not getting the correct o/p.

    Code:
    class CString 
    { 
    public:
    	wstring wStr; 
                    int getLength();
                    CString& TrimLeft(wchar_t* wcChar);
    };
    
    CString& CString::TrimLeft(wchar_t* wcChar)
    {
    	wstring::iterator iterCString = wStr.begin();
    	int iLength = this->getLength();
    	wchar_t* wcTemp = wcChar;
    
    	while (*wcTemp != L'\0')
    	{
    		if (*iterCString == *wcTemp)
    		{
    			wStr.erase(0, 1);
    			iterCString++;
    			wcTemp = wcChar;
    			iLength = this->getLength();
    		}
    		else
    		{
    			wcTemp++;			
    		}
    	}
    	return *this;
    }
    
    int main()
    {
         	CString name = L"!?%@ VIPUL";
    	wcout<<name.wStr<<endl;
    	wchar_t wcArray[5];
    	wcArray[0] = L'%';
    	wcArray[1] = L'!';
    	wcArray[2] = L'?';
    	wcArray[3] = L'@';
    	wcArray[4] = L' ';
    	name.TrimLeft(wcArray);
    	wcout<<name.wStr<<endl;
    	return 0;
    }
  • bajajv
    New Member
    • Jun 2007
    • 152

    #2
    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.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Code:
      wStr.erase(0, 1); 
                  iterCString++;
      The erase invalidates the iterator.

      Comment

      • RRick
        Recognized Expert Contributor
        • Feb 2007
        • 463

        #4
        The correct use of erase is
        Code:
         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.
        Code:
         iterCString = wStr.erase( iterCString);

        Comment

        Working...