Trim a String
Spaces or special characters are very common in Strings. So it is important to know how to trim such characters in String.
Below is a Simple Solution
1) Iterate through all characters of given string, do following
a) If current character is a space, then move all subsequent characters one position back and decrease length of the result string.
The time complexity of the above solution is O(n2).
A Better Solution can solve it in O(n) time. The idea is to keep track of count of non-space character seen so far.
1) Initialize ‘count’ = 0 (Count of non-space character seen so far)
2) Iterate through all characters of given string, do following
a) If current character is non-space, then put this character at index ‘count’ and increment ‘count’
3) Finally, put ‘\0’ at index ‘count’
Contact Us