Sample - C-String Truncation: Notes Code
#include "iostream.h" //for cout #include "string.h" //for strlen, strcpy void TruncateString( char* pszString, char* pszResult ); int main(int argc, char* argv[]) { char szString[] = "MSFT "; char szResult[10]; cout << "Initial String: " << szString << " Length: " << strlen(szString) << endl; TruncateString("MSFT ", szResult ); cout << "Result String: " << szResult << " Length: " << strlen(szResult) << endl; } void TruncateString( char* pszString, char* pszResult ) { int iStringLength = strlen(pszString); char szResult[100]; for ( int i=0; i < iStringLength; i++) { if( *pszString != char(32)) //32 is ASCII for space { szResult[i] = *pszString; pszString++; } else { szResult[i] = '\0'; break; }; /*********************************************************************** * If space not found (end of iteration reached) * * we must write terminating character * ************************************************************************/ if( i == iStringLengh-1) { szResult[i+1] = '\0'; }; }; strcpy(pszResult, szResult); };
Console Output:
Initial String: MSFT Length: 16 Result String: MSFT Length: 4
2002, Netston Consulting