optimization
Apr 23, 2011 at 12:14am UTC
i spent the last 20 or so minutes writing a program to remove all the spaces from a string, and it works perfectly but i feel like the code could be cleaner/neater. anyone have advice for optimizing it? any constructive criticism is welcome :) thanks!
code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include<iostream>
#include<cstring>
using std::cout;
using std::endl;
using std::cin;
char * removeSpace(char * string, int length, char * spaceless, int & spaceCounter);
int main(void )
{
char string[10] = "a b c d e" ;
int length = sizeof (string)/sizeof (string[0]);
char * spaceless = new char [length];
int spaceCounter = 0;
spaceless = removeSpace(string, length, spaceless, spaceCounter);
for (int i = 0; i < spaceCounter; i++)
cout << spaceless[i];
cout << endl;
delete [] spaceless;
spaceless = 0;
return 0;
}
char * removeSpace(char * string, int length, char * spaceless, int & spaceCounter)
{
for (int i = 0; i < length; i++)
{
if (string[i] == ' ' )
continue ;
else
{
spaceless[spaceCounter] = string[i];
spaceCounter++;
}
}
return spaceless;
}
Topic archived. No new replies allowed.