Friday, August 19, 2011

String reversal with words in tact!!

I am on a freaking C programming spirit for past two days!! I feel like coding all the way!!

Problem statement
===============================================

Reverse a string with words, with words intact.
Example will make it explain better 

Input string:: "I am a programming freak!"
Output :: "freak! programming a am I" 



Another -- "I use Mac book" i.e. "book Mac use I"
===============================================
Here is my working Solution!!
===============================================

<pre class="prettyprint">
int main()
{
    char *orig_str = NULL;
    char *rev_str;
    char str[80]; //This is a limitation right now
    char delims[] = " ";
    int orig_len,len =0,slen =0;

    printf("Please enter the string you want to reverse in words\n");
    fgets(str, 80, stdin); //fgets has ugly trailing '\n' too
    len = strlen(str);
    
    if (str[len-1] == '\n')
        str[len-1] = '\0';

    orig_len = len = strlen(str); //new str len with out \n

    rev_str = (char *)malloc(len+1);
    rev_str[len] = '\0';

    orig_str = strtok(str, delims);
    while (orig_str != NULL) {
            slen = strlen(orig_str);
    
            //this to prevent adding space for the first word
            //in orig_str which will be the last in rev_str
            if (len < orig_len)
               strncpy(&rev_str[len]," ",1);

            len = len - slen;
            strncpy(&rev_str[len],orig_str,slen);

            len--;  // for space added to the rev_str

            orig_str = strtok(NULL,delims);
    }
    printf("\nString reversed in words is :\"%s\"\n",rev_str);
    free(rev_str);
}
 

No comments: