In this tutorial you will learn about the C Program to remove all extra Spaces from String and its application with practical example.
C Program to remove all extra spaces from String
In this tutorial, we will learn to create a C program that will remove all extra Spaces from String using C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- While loop in C Programming.
Remove all extra Spaces from String
As we all know array is a collection of similar data type elements. In an array, only one variable is declared which can store multiple values. First will take the number of elements of an array from the user as a string. Then we will remove the extra spaces for a string using a while loop. With the help of C Programming Language.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the string from the user. 3. Sending that string to while loop. 4. Sorting the string and removing the. 5. Printing the results. 6. End program. |
Program:-
Remove all extra Spaces from String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <stdio.h> int main() { //declaring the variables char str[100], blank[100]; int c = 0, d = 0; //Taking the input from the user printf("Enter some text\n"); gets(str); //filtering the string while (str[c] != '\0') { if (!(str[c] == ' ' && str[c+1] == ' ')) { blank[d] = str[c]; d++; } c++; } blank[d] = '\0'; //printing the output printf("Text after removing blanks\n%s\n", blank); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- str[100] = it will hold the elements in an array.
- blank[100] = it will hold the number of elements in an array.
- c = it will hold the integer value to control the array.
- d = it will hold the value of the blank space to be removed.
Taking input from the user in an array as a string to sort and remove extra spces.
Filtering the string value by removing the extra spaces using While Loop.
Printing output without extra blank spaces.