Monday, June 17, 2013

Move spaces from string to start of the string

We can move the spaces from given string at start easily, if we traverse the string from end. Whenever we encounter space while traversing the string from end just copy next character at the location of space and go on copying rest characters in the same fashion. This method take two iteration, one for finding out the end of string second to move the space.

Method MoveSpacesAtStart does the same. It first finds out the end of string and then starts searching spaces back words. This method maintains the character sequence except for the spaces, if we were allowed to alter the character sequence this can be done with single iteration as well.


//Method for moving all spaces from the string at start using only two iterations of the string
#include <iostream>
using namespace std;

void MoveSpacesAtStart( char * inputString )
{
    if ( NULL == inputString )
    {
        return;
    }

    cout << "Before : " << endl << inputString << endl;
    char * end = inputString;
    char * temp = NULL;
    while( *(end + 1) != '\0' )
    {
        end++;
    }

    temp = end;
    int spacecounter = 0;
    while( end != inputString )
    {
        if( *end == ' ' )
        {
            spacecounter++;
        }
        else
        {
            *temp = *(temp - spacecounter);
            temp--;
        }
        end--;
    }

    *temp = *(temp - spacecounter);
    temp--;

    while( temp != inputString)
    {
        *temp = ' ';
        temp--;
    }

    *temp = ' ';

    cout << "After: " << endl << inputString << endl << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char myStr[4][38] =    {{"This is the string I wanted to input."},
                         {"        the string I wanted to input."},
                         {"This is the string.                  "},
                         {"T i i s t e s r n  I w nt d to i p t."}
                      };
    for( int ctr = 0; ctr < 4; ctr++ )
        MoveSpacesFromEnd( myStr[ctr] );  
    return 0;
}

Out put of the above program is shown below


Before :
This is the string I wanted to input.
After:
       ThisisthestringIwantedtoinput.

Before :
        the string I wanted to input.
After:
             thestringIwantedtoinput.

Before :
This is the string.
After:
                     Thisisthestring.

Before :
T i i s t e s r n  I w nt d to i p t.
After:
                 TiistesrnIwntdtoipt.

No comments:

Post a Comment