Solved

reverse a string

Posted on 2004-09-09
12
393 Views
Last Modified: 2010-04-15
How to reverse a string?
For example I have this...
"Hi there right here"   ->  "here right there Hi"

Please help.. I got no idea how to reverse it.. My skills only allow me to reverse characters not words :(
0
Comment
Question by:cutie2000
12 Comments
 
LVL 22

Accepted Solution

by:
NovaDenizen earned 125 total points
ID: 12017812
This is an old-as-the-hills programming puzzle. Reverse the entire string of characters, then reverse the characters in each individual word.
0
 
LVL 22

Expert Comment

by:grg99
ID: 12017951
Here's an algorithm:

you have a string "str", actually in C an array of char;

make a new string, call it Out, set it to empty.

make an array of integers,lets call it "ws"  for "word starts".

Now go thru the string a character at a time, say by indexing:   str[ ThisCol ]

if the current character is the start of a word, note it's place into the next empty slot in ws.

(The start of a word is something like: it's a letter, the first one after a space, or at column 1.)

Now go thru the ws array from the end to the beginning.  Take each word start, and append each character to the output string until you get to the end of the word.  (You can figure out the end of the word either by looking at the character, or by looking to see if you've hit the next start column as listed in "ws".)

Watch out, there are a few nasty boundary conditions  which you can get around by either adding some sentinels, or by checking with if() statements.


0
 
LVL 3

Expert Comment

by:gillgates
ID: 12018064
I am only providing the code because I hope this is not a HW assignment, well not the whole assignment.  If this is the whole assignment, please don't ask us to do it.

#include <stdio.h>
#include <string.h>

void main()
{
      char word[80];
      int length;
      char temp[80];
      int i;

      strcpy(word, "here right there Hi");

      length = strlen(word);

      for(i=0; i<length; i++)
      {
            temp[i] = word[length - 1 - i];
      }

      temp[i] = 0;

      printf("%s", temp);

      return;
}
0
 

Author Comment

by:cutie2000
ID: 12018469
Indeed.. It is a homework but I am proud to say based on the accepted answer (idea is good), I code it myself.


               /* reverse the entire string */
      reverse(temp_str);

      /* here we try to reverse characters in each word */
      token = strtok(temp_str, " ");
      while( token != NULL )
      {
            reverse(token);
            strncat(reverse_str, token, strlen(token));
            token = strtok(NULL, " ");
            if ( token != NULL )
                  strncat(reverse_str, " ", 1);
      }

....


void reverse(char s[])
{
      int c, i, j;
   
      for (i=0, j=strlen(s)-1; i < j;i++, j--)
      {
            c = s[i];
            s[i] = s [j];
            s[j] = c;
      }
}


YEAH!!!
0
 
LVL 1

Expert Comment

by:gethemant
ID: 12026332
Here is yet another code that uses Recursion,it may be useful:

#include <stdio.h>

void reverse();
int main()
{
  reverse();
  return 0;
}
void reverse()
{
   char ch;
   if((ch=getchar())!='\n')
     reverse();
    putchar(ch);
}

The logic is simple,each time when you enter a character the character(along with function) is pushed on the stack and when when the call returns to the function the character is popped
0
 
LVL 22

Expert Comment

by:NovaDenizen
ID: 12027182
When no newline is present on the input, getchar() returns -1 and your program goes into an infinite recursive loop.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 1

Expert Comment

by:gethemant
ID: 12036580
Yeah that is quite obvious.....But the program assumes that the  string ends with a newline!!!
And i think that is almost correct.Anyway...i just gave my idea that recursion can be used!!

On run time basis my code will beat all other Algorithms..
0
 
LVL 22

Expert Comment

by:NovaDenizen
ID: 12044721
>  Yeah that is quite obvious.....But the program assumes that the  string ends with a newline!!!
Your mistaken assumptions, as far as I can tell, are:
1.  The task was to write a program.
cutie2000 never said whether the task was to write a function or a program or just a code snippet.

2.  The task involved reading a string from stdin.
cutie2000 never said that.  The only question asked was how to reverse the words in a string.

3.  The task involved writing the reversed string to stdout.
cutie2000 never said that.  The only question asked was how to reverse the words in a string.

4.  The string to be reversed contained a newline.
This is a bad assumption, and there were no contextual clues to encourage this idea.

5.  Your recursive code is faster than iterative code.
Do actual timing tests, then get back to us.  I think you'll find that your program wastes a great deal of time setting up stack frames and calling functions, not to mention the fact that you output the string with a bunch of putchar() functions despite the fact that outputting the string was not part of the task description.
0
 
LVL 1

Expert Comment

by:gethemant
ID: 12051053
I don't know why you are adamant on proving that your code was better...All i can say is go ahead!!!

But for checking the code performance..i need your code..
you haven't posted any!!!
0
 
LVL 22

Expert Comment

by:NovaDenizen
ID: 12055689
Ok, I'll post code if you first do the following:

1.  Look up the word "sophomoric" in the dictionary and learn what it means.
2.  Explain exactly how your code manages to reverse the order of words in its input.  Hint:  your code doesn't do it.
0
 
LVL 1

Expert Comment

by:gethemant
ID: 12060240
Novadenizen writes:
>>cutie2000 never said whether the task was to write a function or a program or just a code snippet.
Yeah,i have already said that is just an idea that recursion can be used.So let me see your code doing the same thing(that my code does) and then let's do a performance analysis.

Why you are so afraid of putting up your code here!!!Empty words doesn't make any sense.You go around critising my code and i can't do the same for you because you haven't posted any!!!Boy!!,I have to agree you are really smart.
0
 
LVL 22

Expert Comment

by:NovaDenizen
ID: 12065143
You're perfectly free to write a really buggy, poorly thought out program, and declare it to perfectly implement some specification you just made up.  Don't let me disrupt your highly important work with my "critising".




0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now