Removing Spaces from the End of a CStringID: Q114590
|
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.
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.
/* 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 query words: kbinf 1.00 1.50 2.00 2.50 2.51 2.52
Keywords : kb16bitonly
Version :
Platform :
Issue type :
Last Reviewed: July 22, 1999