Registration Forgot password?
Login
Password
Remember me
Login through VKontakte
General > Articles > Function trim on С++ for char*

Realization trim on C++ for char* with example

Parameters:

  1. char* Str - string for trim (can't be const)
  2. int Type - type of trim
    • TRIM_LEFT - trim space only from left side
    • TRIM_RIGHT - only from right side
    • TRIM_BOTH - from both sides

#define TRIM_LEFT 0 // 
#define TRIM_RIGHT 1
#define TRIM_BOTH 2

int trim(char* Str, int Type) {
	int StrLn = strln(Str) + 1;
	if ((StrLn == 0) || (Type < TRIM_LEFT) || (Type > TRIM_BOTH)) {
		return 0;
	}
	char *NewStr = new char[StrLn];
	int IdxSrc = -1, IdxDest = 0;
	if ((Type == TRIM_LEFT) || (Type == TRIM_BOTH)) {
		bool InText = false;
		while(Str[++IdxSrc]) {
			if (!InText && (Str[IdxSrc] != ' ') && (Str[IdxSrc] != '\n') && (Str[IdxSrc] != '\t')) {
				InText = true;
			}
			if (InText) {
				NewStr[IdxDest++] = Str[IdxSrc];
			}
		}
		NewStr[IdxDest] = '\0';
	} else {
		IdxDest = StrLn - 1;
		strcpy_s(NewStr, StrLn, Str);
	}
	if ((Type == TRIM_RIGHT) || (Type == TRIM_BOTH)) {
		while(--IdxDest > 0) {
			if ((NewStr[IdxDest] != ' ') && (NewStr[IdxDest] != '\n') && (NewStr[IdxDest] != '\t')) {
				break;
			}
		}
    NewStr[IdxDest] = '\0';
	}
	strcpy_s(Str, StrLn, NewStr);
	delete NewStr;
	return IdxDest;
}

int main() {
 char *Str = new char[9];
 strcpy_s(Str, 9, " hello ");
 trim(Str, TRIM_BOTH);
 std::cout << "#" << Str << "#" << std::endln;
 _gecth();
 return 0;
}
You can add comment on current page, or on forum page there.Post count 5.

Last comment

13.07.2016
I read your post and wihsed I was good enough to write it http://goaaychrey.com [url=http://sxmboimath.com]sxmboimath[/url] [link=http://pkmmzepl.com]pkmmzepl[/link]
11.07.2016
Didn't know the forum rules allowed such bralilint posts.
10.07.2016
Too many coelipmmnts too little space, thanks! http://opifoqqw.com [url=http://zcqgxhzh.com]zcqgxhzh[/url] [link=http://lkbsgt.com]lkbsgt[/link]

Name*E-mail
Code*