Replace Spaces
You have been given a string 'STR' of words. You need to replace all the spaces between words with “@40”.
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain a single string 'STR' consisting of one or more words.
Output Format:
For each test case, return the modified string after replacing all the spaces between words with “@40”.
Print the output of each test case in a separate line.
Note:
You don’t need to print anything, It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
0 <= |STR| <= 100
Where ‘|STR|’ is the length of a particular string including spaces.
Time limit: 1 sec
The basic idea is to use a separate string to store the resultant string. Copy characters from the original string to the resultant string one by one, and whenever there comes a space, simply add “@40” in the resultant string in place of the space.
The steps are as follows:
- Initialise a string let’s say 'RES, to store the resultant string.
- Start traversing through the string one by one and do the following:
- If you come through space:
- Add “@40” in place of space.
- If it is any other character:
- Simply add the character.
- If you come through space:
- Return the resultant string ‘RES’.
The basic idea of this approach is to assume that string have extra space in the input string.
For example:
S: “Coding Ninjas “
Extra space, in the end, can be used to add @40 in the string
Output: Coding@40Ninjas
In this approach, we will be counting the number of spaces in the string and then calculate the length of the resultant string using that count.
For example:
S: “Coding Ninjas“
‘SPACECOUNT’ = 1
Length of resultant string: (length of string) + ‘SPACECOUNT’ * 2 - 1
Now start replacing spaces from the end with “@40”
String updated
The steps are as follows:
- Count spaces and find the current length
- Remove the trailing spaces
- Find the new length using:
- new length: length + ‘SPACECOUNT’ * 2 - 1
- Start filling character from the end
- Insert “@40”, in place of space
- Return the string.