-2

I want reverse the string in particular format.

For example, "My name is Nishant" should be converted to "Nishant is name My".

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • 1
    What do you have so far? – Codo Aug 29 '11 at 12:04
  • 2
    Dup of [Reversing words in a sentence](http://stackoverflow.com/questions/3276582/reversing-words-in-a-sentence), [c program on reversing a sentence](http://stackoverflow.com/questions/4705069/c-program-on-reversing-a-sentence) – outis Aug 29 '11 at 12:06
  • 2
    What have you tr... oh, right, what Codo an Pierre said. – salezica Aug 29 '11 at 12:06
  • Also, if this is [homework](http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions) it should be mentioned in the question. – outis Aug 29 '11 at 12:10
  • No, it was askedd in my interview – Nishant Aug 29 '11 at 19:07
  • input- My name is Nishant and output-Nishant is name my it should be done without using c lib function.It was asked in my interview. – Nishant Aug 29 '11 at 19:08

2 Answers2

1

If you have your words in a char[] words array then it is a simple loop:

for (i = 0; i < mid; i++)
    exchange(words[i], words[number_of_words - i]);

for sane definitions of mid, number_of_words and exchange.

If all you have is a big char containing the entire statement, doing a strtok first is helpful. Then, use the above loop.

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
0

Give our regards to your instructor. If this is a homework assignment, you should write the code yourself.

Here is a little hint, though: use a char pointer to iterate through each character in the array until you hit the NUL terminator at the end. Now iterate in reverse until you hit a space. Save your place in another pointer, move forward by one then copy each of the characters up to but not including the NUL into your output buffer.

Now retrieve the position of that last space in that other pointer where you saved your place, and back up again. When you move forward, you actually need to stop when you encounter either a space of a NULL - ASCII '\0' or a zero byte - and not just a NUL.

It would be a little faster if you save the positions of each of the spaces in some kind of list as you iterate forward at the beginning. That way you don't then need to iterate backward over the entire string, with short iterations over each word. The code would be a little more complicated.

The increased efficiency would be insignificant for short strings like individual English sentences, but would be quite a lot of you were reversing a large file that you just read into memory.

Mike Crawford
  • 2,232
  • 2
  • 18
  • 28