Write a method to replace all the spaces in a string with ‘%20’. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the “true” length of the string.
Input : "Mr John Smith", 13 Output : Mr%20John%20Smith Input : "Mr John Smith ", 13 Output : Mr%20John%20Smith
A simple solution is to create an auxiliary string and copy characters one by one. Whenever a space is encountered, place %20 in place of it.
A better solution to do in-place assuming that we have extra space in input string. We fist count number of spaces in input string. Using this count, we can find length of the modified (or result) string. After computing new length we fill the string in-place from end.
Time Complexity : O(n) where n is the true length of the string.
Auxiliary Space : O(1) because the above program is an inplace algorithm.
Trim the string and call replaceAll() method, to replace all space unicode to %20.
This article is contributed by Brahmani Sai. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
- String containing first letter of every word in a given string with spaces
- Remove spaces from a given string
- Remove extra spaces from a string
- C++ Program to remove spaces from a string
- Removing spaces from a string using Stringstream
- How to remove all white spaces from a String in Java?
- Move spaces to front of string in single traversal
- Python code to move spaces to front of string in single traversal
- Replace two substrings (of a string) with each other
- Replace a character c1 with c2 and c2 with c1 in a string S
- Replace all occurrences of pi with 3.14 in a given string
- Replace all occurrences of a string with space
- Replace all occurrences of string AB with C without using extra space
- Replace every consonant sequence with its length in the given string
- Program to replace every space in a string with hyphen