Question

Reverse words in sentence while keeping position of white space

Asked by: maximteo

Hi guys, something i couldn't figure out....

Write a function to reverse the order of words

Given a sentence of words in a character array, write a C function to reverse the order of words.

char* reverse_word (char* str);

The function gets a character array as its sole argument, reverses the order of words in it, and puts back the result into it. It returns the pointer to the argument on termination for convenience sake.

See the following example.
char str[] = "this     is very beautiful   ";
printf ("[%s]\n", reverse_word(str));   /* print [beautiful     very is this   ] */

Be ware that the position of space characters has not moved; the result of the example above is [beautiful     very is this   ], not [beautiful very is     this   ].

The following constraints apply:
No external function calls. (strlen, strcpy, etc).
No explicit memory allocation. (malloc, realloc, dynamic arrays, etc)

I managed only managed to reverse the order of words which results in [beautiful very is     this   ], however I didn't know how to maintain the position of space characters [beautiful     very is this   ].

this is the code that i wrote:

#include <stdio.h>
char* reverse_word(char* s)
{
    char *str = s;
    int len = string_len(s);
    int i=0;
    int count=0;
   
    reverse_substring(str,0,pos_lastChar(str));
    while(i<=len){
        if(str[i] ==' ' || i==len){
            reverse_substring(str,i-count,i-1);
            count=0;    
        }  
        if(str[i]!=' '){
            count++;
        }
        i++;
    }
    return str;
}

int pos_lastChar(char* s)
{
    int i;
    for(i=string_len(s); i>0;i--){
        if (s[i]!=' ' && s[i]!='\0'){
            return i;            
        }
    }
}

reverse_substring(char* s, int start, int end)
{
    char temp;
    int i,j;
    for(i=start, j=end; i<j; i++,j--)
    {
        temp = s[i];
        s[i]=s[j];
        s[j]=temp;
    }
}    
int string_len(char* str)
{
    int x=0;
    while(*str++){
        x++;
    }
    return (x);
}

int main(int argc, char **argv)
{
    char str[] = "this is   very beautiful   ";
    printf("Length of string: %d\n",string_len(str));
    printf("[%s]\n", reverse_word(str));
}

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-07-18 at 07:34:40ID21495195
Tags

reverse

,

words

,

sentence

Topic

C Programming Language

Participating Experts
6
Points
250
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Word and Sentence count in a Paragraph, entered by a us…
    Can someone please help me out on the source code for this program? If possible, i'd love to receive reply(ies) before 12th November, 2002. Thank You very much. Write a program in ANSI C that counts words and sentences in a paragraph of English Text entered by the user. Mar...
  2. How to receive a full sentence in input(scanf)?
    Hi: I am having difficulty to write the scanf function for receiving a sentence. This is what I wrote.. main() { char str[30]; char ToFind[30]; printf("Please enter a word: "); scanf("%s",&ToFind); printf("Pl...
  3. printf and scanf
    I am trying to scan a word (string) in middle of a sentence. i am using printf and scanf.... (probably thats very basic, but i am still new to the stuff). i want to input a word and then be able to continue with the phrase without going to the next line example printf("...
  4. Random Sentence Generator
    I need the solution, code, source, whatever on this question. "Write a program that uses random number generation to create sentences. The program should use four arrays of pointers to CHAR called article, noun, verb and preposition. The program should create a sentence ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: PaulCaswellPosted on 2005-07-18 at 08:19:15ID: 14466967

maximteo,

Nice to see this old homework chestnut. Thankyou for showing it to us again!

This seems to me like a rather complicated way to achieve the required result. You are taking every space-delimited string in the string and reversing it, i.e. steps look like:

0. "this     is very beautiful   "
1. "lufituaeb yrev si     siht   "
2. "beautiful yrev si     siht   "
...

I would have thought you should follow the plan:

1. Find the starts of all the words in the string.
2. Swap all the words in the string.

Paul

 

by: maximteoPosted on 2005-07-18 at 08:39:23ID: 14467206

Hi paul,

Could u provide me with a code snipplet based on ur plan ?

maximteo

 

by: PaulCaswellPosted on 2005-07-18 at 08:50:11ID: 14467345

maximteo,

This would be very difficult at this stage. You must do the work and we will correct it. Start with trying to find the start of the next word in the string given a place to start:

int findStartOfNextWord ( char * s, int start )
{
  // Step to the end of this word.
  ...

  // Skip spaces
  ...
}

Paul

 

by: slyongPosted on 2005-07-18 at 20:00:25ID: 14472181

hi maximteo,

I just like to show you some strategies...  I think with your understanding of C you should be able to implement it quite easily...

[this   is very beautiful ] <-- find begin of left first word & right first word
[bhis   is very teautiful ] <-- swap the characters while not ' '
[beis   is very thautiful ]
[beas   is very thiutiful ]
[beau   is very thistiful ]
[beaut   is very thisiful ] <-- space detected on left word, start shifting right
[beauti   is very thisful ]
[beautif   is very thisul ]
[beautifu   is very thisl ]
[beautiful   is very this ] <-- find begin and end of next left word & right word
[beautiful   vs iery this ] <-- swap the characters while not ' '
[beautiful   ve isry this ]
[beautiful   ver isy this ] <-- space detected on left word start shifting right
[beautiful   very is this ] <-- end

Another example...
[beautiful   is very this ] <-- find begin of left first word & right first word
[teautiful   is very bhis ] <-- swap the characters while not ' '
...
[thistiful   is very beau ] <-- space detected on right word, start shifting left
[thisiful   is very beaut ]
...
[this   is very beautiful ] <-- find begin and end of next left word & right word
[this   vs iery beautiful ] <-- swap the characters while not ' '
[this   ve isry beautiful ] <-- space detected on left word, start shifting right
[this   ver isy beautiful ]
[this   very is beautiful ] <-- end

Cheers,
slyong

 

by: ShweetaPosted on 2005-07-18 at 20:54:04ID: 14472321

hey, pressed the submit by mistake. Writing again :)

Just a two step process:

This<space><space>is<space><space><space>good

1. Reverse the line
      - the usual, use to counters (use pointers :)), one start of line, one end of line.
      - start loop
             - swap
             - increment counter 1 and decrement counter 2 inside the loop.
             - increment or decrement only if the character is not a <space>.

Step 1 would result in

doog<space><space>si<space><space><space>sihT

2. Now reverse the individual words.

Step 2 would result in

good<space><space>is<space><space><space>This


Shweta
     

 

by: maximteoPosted on 2005-07-19 at 08:33:23ID: 14476077

thanx guys i'm still trying to work it out based on the example slyong has explained...will update with a working code ..
anymore advice would be helpful too :)

 

by: PaulCaswellPosted on 2005-07-19 at 08:54:22ID: 14476367

I think the idea slyong suggests will produce an unnecessarily complicated result.

Break the problem down into parts! You will need to perform the following functions.

1. Find a complete word, starting at a specific position in a particular direction.
2. Swap two words.

Once you've achieved each of these, you're most of the way there.

Finding words is a sequence of loops which move a pointer back or forward (depending on the direction specified) until its passed a sequence of non-spaces then a sequence of spaces, stopping at the end or start of the string.

Swapping two words is just a matter of:

a. Copy the largest one out.
b. Copy the smallest into the gap left by the largest.
c. Shuffle the data so that the gap is now at the end of the smallest and is therefore big enough to take the largest.
d. Copy the largest in.

...short....muchlonger...

after a. and b.

...short....shortonger...

after c.

...short....s....short...

after d.

...muchlonger....short...

You will learn much more about programming by doing it the grown-up way of breaking the problem into smaller parts untill each is do-able than just achieving the output the customer(teacher) requested.

Paul

 

by: gtkfreakPosted on 2005-07-19 at 11:13:44ID: 14477928

You can also do it by finding the length of the source string, using a for loop counting down and pushing characters into the destination string.

 

by: KdoPosted on 2005-07-19 at 13:55:53ID: 14479498


Yep.  There are lots of ways to do this.

I'd use a recursive algorithm.
Kent

 

by: slyongPosted on 2005-07-19 at 17:39:29ID: 14480760

I think the major problem that the thing get a bit complicated is the restriction on dynamic memory allocation which I supposed, it also means that one is not allow to cheat by allocating a char myString[INT_MAX] or do something like char myString[string_len(str)].

This leave ones the only choice of allocating char and swapping and shiftting those characters around the original array.  May be maximteo can englighten us on that part.  If things like myString[INT_MAX] is allowed then Paul's idea of finding the words and swapping them word by word would be much simpler then implementing something like my idea.

 

by: maximteoPosted on 2005-07-19 at 18:21:13ID: 14480923

Hi Slyong,

this was an interview question which i failed to answer =(
unfortunately myString[string_len(str)]  is explictly allocating memory which is the restriction here too.

Slyong, I'm wondering when u mentioned "[beaut   is very thisiful ] <-- space detected on left word, start shifting right"
wat do u mean by start shifting right ?

My understanding from what u said is to shift the index position of the rest of the chars ?
e.g {before shift} [beau   is very thistiful ] current position of 'i' in 'is' = 7
      {after shift}   [beaut   is very thisiful ] position of 'i' in 'is' = 8

so every character after 'beaut' gets shifted/pushed to the right shifting one index ?

if my understanding is correct, could u give a code sniplet to demonstrate how u'd do this ? (i'm just wondering if this is similar to insertion sort)

       

 

by: slyongPosted on 2005-07-19 at 19:55:47ID: 14481259

Hi maximteo,

just hack up something.. may not work properly.. but you can have a look.  But sorry this is the maximum I would go for code sniplet.  If you could understand shift_right, you could hack up shift_left quite easily... also I have not really done a proper testing on this.. so bugs here and there..

#define SWAP 0
#define SH_L 1
#define SH_R 2

int swap_string(char *str, int *l_pos, int *r_pos) {
  char tmp;

  while (str[*l_pos] != ' ' && str[*r_pos] != ' ') {
    tmp = str[*l_pos];
    str[*l_pos] = str[*r_pos];
    str[*r_pos] = tmp;
    (*l_pos)++; (*r_pos)++;
  }

  if (str[*l_pos] == ' ')
    return SH_R;  /* return what to do next */
  else
    return SH_L;
}

int shift_right(char *str, int *l_pos, int *r_pos) {
  char tmp;
  int i;

  while (str[*r_pos] != ' ') {
    tmp = str[*r_pos];
    for (i = *r_pos; i > *l_pos; --i) {
      str[i] = str[i - 1];
    }
    str[*l_pos] = tmp;
    (*l_pos)++; (*r_pos)++;
  }
  return SWAP;
}

int main(int argc, char *argv[])
{
  char str[] = "this   is very beautiful ";
  int cur_l_pos = 0, cur_r_pos = 24; /* I cheat a bit here... */
  int next_op;

  next_op = swap_string(str, &cur_l_pos, &cur_r_pos); /* next_op should tell me what to do next */
  printf("SWAP %d:%d [%s]\n", cur_l_pos, cur_r_pos, str);

  shift_right(str, &cur_l_pos, &cur_r_pos);
  printf("SH_L %d:%d [%s]\n", cur_l_pos, cur_r_pos, str);

  return EXIT_SUCCESS;
}

 

by: slyongPosted on 2005-07-20 at 03:16:58ID: 14482883

Paul,

Sorry bout that.  My bad.  I won't mind if it is removed.

slyong

 

by: stefan73Posted on 2005-07-20 at 03:18:53ID: 14482893

Hi maximteo,
Basically, you need to split up the input string into two different things:
1. The words themselves
2. The spacings

To reassemble the string in inverse order is relatively simple. Assuming your original string is consisting of W/S sequences (word/space):

original:
W1 S1 W2 S2 ... Sn-1 Wn

Split up:
Spaces: S1 S2 ... Sn-1 (there's always one spacing less)
Words: W1 W2 ... Wn

Reassemble:
Wn S1 Wn-1 S2 ... Sn-1 W1

...finished.

Start with the spacings. Since a space is a space, an array of space sizes is sufficient. Hint: check the isspace() function.
Then divide up the string words. Hint: check the strtok() function.

That should be enough to get you going.

Cheers!

Stefan

 

by: PaulCaswellPosted on 2005-07-20 at 04:35:29ID: 14483283

Stefan,

All good points but one heads up:

>>(there's always one spacing less)
" there could be spaces at the start and the end so I think its the other way around " ;)
There could be one MORE space-run that words.

Paul

 

by: stefan73Posted on 2005-07-28 at 12:22:29ID: 14549114

Paul, you're right ;-)

Hmm, in this case you could simply use a lambda-word "".

Stefan

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...