Tuesday, February 28, 2012

Remove extra spaces in string on c++

Hi, right now I'll show you how to remove extra spaces in string on C++. So.....here is the code.


#include "stdafx.h"
#include <iostream>
using namespace std;

bool del(char* str1)
{
 char* str = new char[80];
 int i = 0;
 int k = 0;
 while(str1[i] != '\0')
 {
  if(str1[i] !=' ')
  {
   str[k] = str1[i];
   ++i;
   ++k;
  }
  else
  {
   if(str1[i+1] != ' ')
   {
    str[k] = str1[i];
    ++k;
   }
   ++i;
  }

 };
 str[k] = '\0';
 delete[]str1;
 str1 = str;
 cout << str1;
 return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
 char* st = new char[80];
 cin >> st;
 del(st);
 cout << st;
 cin.get();

 cin.get();
 cin.get();
 return 0;
}