• C

reverse a string

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 :(
cutie2000Asked:
Who is Participating?
 
NovaDenizenCommented:
This is an old-as-the-hills programming puzzle. Reverse the entire string of characters, then reverse the characters in each individual word.
0
 
grg99Commented:
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
 
gillgatesCommented:
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
WEBINAR: 10 Easy Ways to Lose a Password

Join us on June 27th at 8 am PDT to learn about the methods that hackers use to lift real, working credentials from even the most security-savvy employees. We'll cover the importance of multi-factor authentication and how these solutions can better protect your business!

 
cutie2000Author Commented:
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
 
gethemantCommented:
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
 
NovaDenizenCommented:
When no newline is present on the input, getchar() returns -1 and your program goes into an infinite recursive loop.
0
 
gethemantCommented:
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
 
NovaDenizenCommented:
>  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
 
gethemantCommented:
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
 
NovaDenizenCommented:
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
 
gethemantCommented:
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
 
NovaDenizenCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.