Wednesday, September 14, 2011

Fast, in-place C string trim

I want to share with the world this code for a fast trim function in C which is part of my personal library, and that I use quite often. It performs both left and right trim as an in-place operation, changing the original string. The return value is the same pointer that was passed as argument.

This is the version I use on Linux:
char* trim(char *s)
{
	char *pRun = s;
	while(*pRun == ' ') ++pRun;
	if(pRun != s)
	memmove(s, pRun, (strlen(pRun) + 1) * sizeof(char));
	pRun = s + strlen(s) - 1;
	while(*pRun == ' ') --pRun;
	*(++pRun) = 0;
	return s;
}
And this is the version I use on Win32, which is Unicode-ready:
LPTSTR trim(LPTSTR s)
{
	TCHAR *pRun = s;
	while(*pRun == TEXT(' ')) ++pRun;
	if(pRun != s)
	memmove(s, pRun, (lstrlen(pRun) + 1) * sizeof(TCHAR));
	pRun = s + lstrlen(s) - 1;
	while(*pRun == TEXT(' ')) --pRun;
	*(++pRun) = 0;
	return s;
}

No comments: