Let there be a string say “I AM A GEEK”. So, the output should be “GEEK A AM I” . This can done in many ways. One of the solutions is given in Reverse words in a string .
Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG
This can be done in more simpler way by using the property of the “%s format specifier” .
Property: %s will get all the values until it gets NULL i.e. ‘\0’.
Example: char String = “I AM A GEEK” is stored as shown in the image below :
Approach: Traverse the string from the last character, and move towards the first character. While traversing, if a space character is encountered, put a NULL in that position and print the remaining string just after the NULL character. Repeat this until the loop is over and when the loop ends, print the string, the %s will make the printing of characters until it encounters the first NULL character.
Let us see the approach with the help of diagrams:
step 1: Traverse from the last character until it encounters a space character .
Step 2: Put a NULL character at the position of space character and print the string after it.
Step 3: At the end, the loop ends when it reaches the first character, so print the remaining characters, it will be printed the first NULL character, hence the first word will be pprinted.
GEEK A AM I
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Reverse words in a given string
- Reverse String according to the number of words
- Reverse middle words of a string
- Reverse words in a given String in Java
- Reverse words in a given String in Python
- Print Fibonacci Series in reverse order
- Print Doubly Linked list in Reverse Order
- Print all funny words in a string
- Print reverse of a string using recursion
- Print reverse string after removing vowels
- Print a number as string of 'A' and 'B' in lexicographic order
- Print all the palindromic permutations of given string in alphabetic order
- Print all distinct characters of a string in order (3 Methods)
- Print array of strings in sorted order without copying one string into another
- Check if the given string of words can be formed from words present in the dictionary