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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if the given string of words can be formed from words present in the dictionary
- Reverse words in a given String in Java
- Reverse words in a given String in Python
- Reverse String according to the number of words
- Reverse middle words of a string
- Program to reverse words in a given string in C++
- Reverse words in a given string | Set 2
- Reverse the Words of a String using Stack
- Reverse words in a given string
- Count words that appear exactly two times in an array of words
- Print Fibonacci Series in reverse order
- Print Doubly Linked list in Reverse Order
- Print Strings In Reverse Dictionary Order Using Trie
- Program to print numbers from N to 1 in reverse order
- Reverse individual words
- Reverse individual words with O(1) extra space
- Print all funny words in a string
- Java program to print Even length words in a String
- Extract and print words separately from a given Camel Case string
- Sort the words in lexicographical order in Python