Removing Spaces from the End of a CString

Last reviewed: July 22, 1997
Article ID: Q114590
1.00 1.50 1.51 1.52 WINDOWS kbprg

The information in this article applies to:

  • The Microsoft Foundation Classes (MFC) included with: Microsoft Visual C++ for Windows, versions 1.0, 1.5, 1.51, and 1.52

SUMMARY

The CString class, which is included in MFC 2.0 and 2.5, does not contain a function that will remove white-space characters from the end of a CString's string. The sample code demonstrates one possible way to write this function.

These steps are not necessary if you are creating a 32-bit application. The 32-bit implementation of CString has member functions TrimRight and TrimLeft, which help you remove leading/trailing blank spaces from the string.

MORE INFORMATION

The following function relies on the current CString interface to work properly. RemEndBlanks() was not written to be Double Byte Character Set (DBCS) aware, but it may work properly because the function only checks for white-space characters, which can be neither leading nor trailing bytes. For more information on DBCS, refer to Tech Note #44, which was released with Microsoft Visual C++ for Windows, version 1.5.

Sample Code

/* Compile options needed: NONE
*/
#include <ctype.h>   // required for isspace C run-time function

void RemEndBlanks(CString &s)
{
  BOOL Done = FALSE;
  int  SLen = s.GetLength();

  if(SLen) {
    // Checks for all white space characters
    for(int Len = SLen-1; Len >= 0 && !Done; --Len) {
      if(!isspace(s[Len]))
         Done = TRUE;
    }
    Len++;        // Add 1 to recover from extra decrement in loop

    if(Len < SLen-1 && Done) // Remove any white space characters
      s = s.Left(Len+1);     // from the end of the string
    else if(!Done)           // If string contains only white space
      s.Empty();             // characters, empty it
  }
}


Additional reference words: kbinf 1.00 1.50 2.00 2.50 2.51 2.52
KBCategory: kbprg
KBSubcategory: MfcMisc
Keywords : kb16bitonly
Technology : kbMfc


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: July 22, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.