First of all according to the assignment you should use a character array. Character array is not std::string class.
As for your algorithm then it is invalid. To understand this try it when the character array consists from four characters that are all spaces.
If you are allowed to use standard algorithms then your assignment is done in one line by means of std::unique.
Careful! Testing for a ' ' char is not the same as a test for an empty string ("")
The solutions are pretty simple (once you see them!), but I think you should try and work it out for yourself. But I will say that the one that occurs to me first needs a second index variable in addition to the one on the loop (but not a second loop).
As it stands, your code is missing some of the blanks which need removing as it only looks for a single pair of blanks before stepping the loop index.
Also, the way you're using the length is suspicious.
- string has a length() method, so there might be no need for the length param. as vlad drew our attention to, the first param should be a char
- why are you returning -1 for the length == 0 case? The return is the number of blanks removed.
Also in my opinion the function does not need the second parameter because the length of a character array thet represents a string is simply determined by finding the nul character.
Moreover the new length of the array is calculated as difference between the old length of the array and the number of removed spaces.
Even if the array does obligatory contain the nul character in any case you can calculate the new length as mentioned above/ So there is no need to declare the second parameter as a reference,
The code is simple if to use pointers.
1 2 3 4 5 6 7 8 9 10 11 12 13
int removeExtraBlanks( char *Sentence, int length )
char *end = s + length;
char *p = s, *q = s;
while ( p < end )
*q = *p++;
if ( *q++ == ' ' ) while ( p < end && *p == ' ' ) ++p;
return ( p - q );
As you can see I removed the reference of the second parameter. The new length can be calculated as difference between the original length and the return value of the function.
Also I assumed that the character array does not contain the nul character.
Sorry, didn't notice that the array must be of type char, well.. now I changed from string to char and edited few things but it became complicated for me.
For andywestken, I used return -1, so when the array is empty, I check the return value in the main function if it's -1 I display an output message telling the user that the array is empty.
For vlad, sorry but I couldn't understand the code you wrote because I am mostly still studying the very basic things of C++, it is like an introduction to it and I didn't learn the purpose of * yet. In addition, I must follow the question details or requirements because my solution will be graded.