Program to Remove All the White Spaces from a String in C
Overview
A String is a collection of characters, and also contains white spaces in between the characters. We can remove the white spaces using transversing the string as well as using recursion.
Introduction
The String is a collection of the same or different characters that are grouped and formed in meaningful sentences. In this article, we will discuss how to remove all the white spaces from the String in the C language.
Algorithm for Removing all the White Spaces from a String
Let's understand the algorithm for removing all the white spaces from a String.
Algorithm:
- Iterate the given string using any kind of loop(for, while) till the length of the String.
- Check the current character, if it is equal to space, we will skip the character.
- Otherwise, store the current character in the current string, and update the size of the string.
Time Complexity
The time complexity of this approach will be O(l), Where l is the length of the given String.
C Program to Remove all the White Spaces from a String
Let's understand how to remove all the white spaces from a String in C language using a program.
In the below program, we are using two indexes i.e i and j. The ith index is used to iterate on the given string, and the jth index is used to remove the white spaces present in between the given string, and at the end, we get an updated string without any kind of white spaces.
Output:
Removing all the White Spaces from a String Using Function
Let's understand how to remove all the White Spaces from a String using a function.
Let's first create a trim() method that trims the left space and the right space of the given string using the ltrim(), and the rtrim() method then after the function remove_space is used to trim the remaining spaces in the given string.
Output:
Removing all the White Spaces from a String Using Recursion
Let's understand how to remove all the White Spaces from a String Using Recursion.
In the below program, we are recursively removing the white spaces from the given string using the recursion.
We recursively iterate the given string using the ith index, and whenever we get an empty space, we just skip the character and recursively call the remaining string.
Output:
Conclusion
- The string is a collection of different characters.
- The time complexity to remove all the white spaces is O(n).